博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python基本数据类型(字典)
阅读量:6671 次
发布时间:2019-06-25

本文共 9214 字,大约阅读时间需要 30 分钟。

基本数据类型

五、字典

字典(Dictionary)是Python中一种由“键-值”组成的常用数据结构。

1.字典格式

Python中使用一对花括号“{}”或者dict()函数来创建字典。

dic = {    "one":1,    "two":2,    "three":3}

 

2.键的不可变性

我们可以将Python中基本数据类型大致分为两类:

  • 不可变类型:数字、字符串、元组
  • 可变类型:列表、字典

故列表、字典不能作为字典的键。

3.从属关系的判断

与列表类似,可以用关键字in来判断某个键是否在字典中:

dic = {    "one":1,    "two":2,    "three":3}a = "one" in dicprint(a)      #结果为:True

判断某个值是否在字典中需要使用values()函数:

dic = {    "one":1,    "two":2,    "three":3}a = 4 in dic.values()print(a)     #结果为:False

4.字典的方法

(1).get()方法

.get()方法根据键获取值,键不存在时,默认值为None。

dic = {    "one":1,    "two":2,    "three":3}a = dic.get("s")print(a)    #结果为:None

(2).pop()方法

.pop()方法删除并返回指定键的值。与列表的.pop()方法不同的是列表根据索引位置删除并返回值,而字典根据键删除并返回值。

dic = {    "one":1,    "two":2,    "three":3}a = dic.pop("one")print(a)      #结果为:1print(dic)      #结果为:{'two': 2, 'three': 3}

(3).update()方法

.update()方法是更新多个键值对。

dic = {    "one":6,    "two":2,    "three":3}a = {    "one":1,    "four":4   }dic.update(a)print(dic)     #结果为:{'one': 1, 'two': 2, 'three': 3, 'four': 4}

(4).keys()方法

.keys()方法返回一个由所有键组成的列表:

dic = {    "one":1,    "two":2,    "three":3}print(dic.keys())    #结果为:dict_keys(['one', 'two', 'three'])

(5).values方法

.values方法返回一个由所有值组成的列表:

dic = {    "one":1,    "two":2,    "three":3}print(dic.values())    #结果为:dict_values([1, 2, 3])

(6).items方法

.items方法返回一个由所有键值对元组组成的列表:

dic = {    "one":1,    "two":2,    "three":3}print(dic.items())     #结果为:dict_items([('one', 1), ('two', 2), ('three', 3)])

字典所有方法归纳:

1 class dict(object):  2     """  3     dict() -> new empty dictionary  4     dict(mapping) -> new dictionary initialized from a mapping object's  5         (key, value) pairs  6     dict(iterable) -> new dictionary initialized as if via:  7         d = {}  8         for k, v in iterable:  9             d[k] = v 10     dict(**kwargs) -> new dictionary initialized with the name=value pairs 11         in the keyword argument list.  For example:  dict(one=1, two=2) 12     """ 13  14     def clear(self): # real signature unknown; restored from __doc__ 15         """ 清除内容 """ 16         """ D.clear() -> None.  Remove all items from D. """ 17         pass 18  19     def copy(self): # real signature unknown; restored from __doc__ 20         """ 浅拷贝 """ 21         """ D.copy() -> a shallow copy of D """ 22         pass 23  24     @staticmethod # known case 25     def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26         """ 27         dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28         v defaults to None. 29         """ 30         pass 31  32     def get(self, k, d=None): # real signature unknown; restored from __doc__ 33         """ 根据key获取值,d是默认值 """ 34         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """ 35         pass 36  37     def has_key(self, k): # real signature unknown; restored from __doc__ 38         """ 是否有key """ 39         """ D.has_key(k) -> True if D has a key k, else False """ 40         return False 41  42     def items(self): # real signature unknown; restored from __doc__ 43         """ 所有项的列表形式 """ 44         """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45         return [] 46  47     def iteritems(self): # real signature unknown; restored from __doc__ 48         """ 项可迭代 """ 49         """ D.iteritems() -> an iterator over the (key, value) items of D """ 50         pass 51  52     def iterkeys(self): # real signature unknown; restored from __doc__ 53         """ key可迭代 """ 54         """ D.iterkeys() -> an iterator over the keys of D """ 55         pass 56  57     def itervalues(self): # real signature unknown; restored from __doc__ 58         """ value可迭代 """ 59         """ D.itervalues() -> an iterator over the values of D """ 60         pass 61  62     def keys(self): # real signature unknown; restored from __doc__ 63         """ 所有的key列表 """ 64         """ D.keys() -> list of D's keys """ 65         return [] 66  67     def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68         """ 获取并在字典中移除 """ 69         """ 70         D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71         If key is not found, d is returned if given, otherwise KeyError is raised 72         """ 73         pass 74  75     def popitem(self): # real signature unknown; restored from __doc__ 76         """ 获取并在字典中移除 """ 77         """ 78         D.popitem() -> (k, v), remove and return some (key, value) pair as a 79         2-tuple; but raise KeyError if D is empty. 80         """ 81         pass 82  83     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84         """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86         pass 87  88     def update(self, E=None, **F): # known special case of dict.update 89         """ 更新 90             {'name':'alex', 'age': 18000} 91             [('name','sbsbsb'),] 92         """ 93         """ 94         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F. 95         If E present and has a .keys() method, does:     for k in E: D[k] = E[k] 96         If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v 97         In either case, this is followed by: for k in F: D[k] = F[k] 98         """ 99         pass100 101     def values(self): # real signature unknown; restored from __doc__102         """ 所有的值 """103         """ D.values() -> list of D's values """104         return []105 106     def viewitems(self): # real signature unknown; restored from __doc__107         """ 所有项,只是将内容保存至view对象中 """108         """ D.viewitems() -> a set-like object providing a view on D's items """109         pass110 111     def viewkeys(self): # real signature unknown; restored from __doc__112         """ D.viewkeys() -> a set-like object providing a view on D's keys """113         pass114 115     def viewvalues(self): # real signature unknown; restored from __doc__116         """ D.viewvalues() -> an object providing a view on D's values """117         pass118 119     def __cmp__(self, y): # real signature unknown; restored from __doc__120         """ x.__cmp__(y) <==> cmp(x,y) """121         pass122 123     def __contains__(self, k): # real signature unknown; restored from __doc__124         """ D.__contains__(k) -> True if D has a key k, else False """125         return False126 127     def __delitem__(self, y): # real signature unknown; restored from __doc__128         """ x.__delitem__(y) <==> del x[y] """129         pass130 131     def __eq__(self, y): # real signature unknown; restored from __doc__132         """ x.__eq__(y) <==> x==y """133         pass134 135     def __getattribute__(self, name): # real signature unknown; restored from __doc__136         """ x.__getattribute__('name') <==> x.name """137         pass138 139     def __getitem__(self, y): # real signature unknown; restored from __doc__140         """ x.__getitem__(y) <==> x[y] """141         pass142 143     def __ge__(self, y): # real signature unknown; restored from __doc__144         """ x.__ge__(y) <==> x>=y """145         pass146 147     def __gt__(self, y): # real signature unknown; restored from __doc__148         """ x.__gt__(y) <==> x>y """149         pass150 151     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__152         """153         dict() -> new empty dictionary154         dict(mapping) -> new dictionary initialized from a mapping object's155             (key, value) pairs156         dict(iterable) -> new dictionary initialized as if via:157             d = {}158             for k, v in iterable:159                 d[k] = v160         dict(**kwargs) -> new dictionary initialized with the name=value pairs161             in the keyword argument list.  For example:  dict(one=1, two=2)162         # (copied from class doc)163         """164         pass165 166     def __iter__(self): # real signature unknown; restored from __doc__167         """ x.__iter__() <==> iter(x) """168         pass169 170     def __len__(self): # real signature unknown; restored from __doc__171         """ x.__len__() <==> len(x) """172         pass173 174     def __le__(self, y): # real signature unknown; restored from __doc__175         """ x.__le__(y) <==> x<=y """176         pass177 178     def __lt__(self, y): # real signature unknown; restored from __doc__179         """ x.__lt__(y) <==> x
a new object with type S, a subtype of T """185 pass186 187 def __ne__(self, y): # real signature unknown; restored from __doc__188 """ x.__ne__(y) <==> x!=y """189 pass190 191 def __repr__(self): # real signature unknown; restored from __doc__192 """ x.__repr__() <==> repr(x) """193 pass194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__196 """ x.__setitem__(i, y) <==> x[i]=y """197 pass198 199 def __sizeof__(self): # real signature unknown; restored from __doc__200 """ D.__sizeof__() -> size of D in memory, in bytes """201 pass202 203 __hash__ = None204 205 dict
dict

 

转载于:https://www.cnblogs.com/lzc69/p/11032673.html

你可能感兴趣的文章
pvst+
查看>>
博为峰Java技术题 ——JavaEE Servlet 国际化Ⅰ
查看>>
layabox基础:hello world
查看>>
ClassUtil
查看>>
Elastic-Job定时任务
查看>>
真实分享记录我学习Linux系统遇到的问题
查看>>
Linux下查找占用内存最多的进程
查看>>
mongodb 配置文件
查看>>
查看 docker 容器使用的资源
查看>>
Jedis的配置和优化
查看>>
layui + 阿里巴巴iconfont图标库导入
查看>>
2017总结一
查看>>
MySQL中TIMESTAMPDIFF和TIMESTAMPADD函数的用法
查看>>
Power Designer数据库建模工具,正向、逆向工程
查看>>
Libevent学习-02:搭建CentOS下的开发环境
查看>>
yum install 与 yum groupinstall 的区别
查看>>
PHP协程入门详解
查看>>
Java_Reflect_1
查看>>
HTML中的<table>标签及其子元素标签,JS中DOM对<table>的操作
查看>>
MobPush推送证书制作
查看>>