python中字典,python访问字典,字典中key:不可改


字典中key:不可改变的数据类型

#fromkeys 快速定义一个空字典

res = {}.fromkeys([‘a‘,‘b‘,‘c‘],[‘1‘,‘2‘,‘3‘])print(res)

技术图片

定义字典:

dict1 = {       ‘name1‘:‘天明‘,    ‘age‘:‘25‘,    ‘high‘:‘170‘}dict2 = {    ‘name2‘:‘tian‘,    ‘age‘:‘25‘,    ‘phone‘:‘100‘}

#[ ] 根据key取值 如果取不到报错

>>> dict1 = {... ‘name1‘:‘天明‘,... ‘age‘:‘25‘,... ‘high‘:‘170‘... }>>> res = dict1[‘name1‘]>>> print(res)天明

res = dict1[‘name11‘] #报错print(res)

技术图片

#get 根据key取value 如果取不到则返回None

res = dict1.get(‘name‘)print(res)

技术图片

#update 一般用来合并字典

dict1.update(dict2)print(dict1)

技术图片

#打印字典里所有的值

print(dict1.values())

技术图片

#打印字典里所有的keys

print(dict1.keys())

技术图片

#打印字典里所有的键值对

print(dict1.items())

技术图片

#pop 根据key剪切(key=name)

res = dict1.pop(‘name1‘)print(res)

技术图片

#clear 清除

dict1.clear()print(dict1)

技术图片

#popitem 从后往前剪切键值对

print(dict1.popitem())

技术图片

python中字典

评论关闭