python中字典

字典中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())

 

 

 

 

 

posted on 2019-11-11 08:33  负重前行岁月静好  阅读(163)  评论(0编辑  收藏  举报