Python内置数据结构之一,是可变序列。
以键值对的方式对应,与 C C C++中的map
类似。
即:key->value
d = {'Flying':100, 'Tom':89} #数据类型为dict
dict
stu = dict(name='Flying', age=19)
print(stu) #相当于字典{'name': 'Flying', 'age': 19}
空字典:
a = {}
[ ]
d = {'Flying':100, 'Tom':99, 'Gray': 89}
print(d['Flying'])
get
函数d = {'Flying':100, 'Tom':99, 'Gray': 89}
print(d.get('Flying')) #100
print(d.get('Fly', 66)) #指定的键不存在给默认值66
print(d)
采用in
或者not in
即可:
d = {'Flying':100, 'Tom':99, 'Gray': 89}
print('Flying' in d) #True
print('Flying' not in d) #False
d = {'Flying':100, 'Tom':99, 'Gray': 89}
del d['Flying'] #删除操作
print(d)
#添加操作
d = {'Flying':100, 'Tom':99, 'Gray': 89}
d['Tim'] = 0
print(d)
d = {'Flying':100, 'Tom':99, 'Gray': 89}
p = d.items()
print(p)
p = d.keys()
print(p)
p = d.values()
print(p)
d = {'Flying':100, 'Tom':99, 'Gray': 89}
for item in d:
print(item, d[item])
语法:{key:value for key,value in zip(keys,values)}
如下:
a = ['Fruits', 'Books', 'Others']
b = [10,20,30]
#字典生成式
d = {item:price for item, price in zip(a, b)}
print(d)
若要key
的字母全部大写,如下:
a = ['Fruits', 'Books', 'Others']
b = [10,20,30]
#字典生成式
d = {item.upper():price for item, price in zip(a, b)}
print(d)