python中字典的基础操作

dict1 = {

'name':'王麻子',
'age':25,
'phone':12580,
'high':160
}
dict2 = {
'name':'张三',
'age':38,
'phone':12580,
'high':160,
'gender':'man'
}  

#copy

>>> dict3 = dict1.copy()
>>> print(dict3)
{'name': '王麻子', 'age': 25, 'phone': 12580, 'high': 160}  

#len()
#测量字典中,键值对的个数

>>> print(len(dict1))
>>> print(len(dict2))
4
5  

#keys
#返回一个包含字典所有KEY的列表

>>> list1 = dict1.keys()
>>> print(list1)
或
>>> print(dict1.keys())
dict_keys(['name', 'age', 'phone', 'high'])  

#values
#返回一个包含字典所有value的列表

>>> list1 = dict1.values()
>>> print(list1)
或
>>> print(dict1.values())
dict_values(['王麻子', 25, 12580, 160]) 

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

>>> print(dict1.items())
dict_items([('name', '王麻子'), ('age', 25), ('phone', 12580), ('high', 160)])  

#pop,根据key剪切,没有报错

>>> res = dict1.pop('name')
>>> print(dict1)
>>> print(res)
{'age': 25, 'phone': 12580, 'high': 160}
王麻子
>>> res = dict2.pop('gender')
>>> print(res)
KeyError: 'gender'  

#clear,清空字典

>>> dict1.clear()
{}  

#fromkeys快速定义一个空字典

>>> res = {}.fromkeys(['a','b','c'],[1,2,3])
>>> print(res)
{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}
>>> res = {}.fromkeys(['a','b','c'],)
>>> print(res)
{'a': None, 'b': None, 'c': None}  

#setdefault设置字典的默认值

>>> dict1.setdefault('gender','man')
>>> print(dict1)
{'name': '王麻子', 'age': 25, 'phone': 12580, 'high': 160, 'gender': 'man'} 

#popitem,从后往前剪切键值对

>>> print(dict1.popitem())
>>> print(dict1.popitem())
>>> print(dict1.popitem())
>>> print(dict1)
('high', 160)
('phone', 12580)
('age', 25)
{'name': '王麻子'}  

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

>>> res = dict1['name1111']
>>> print(res)
res = dict1['name1111']
KeyError: 'name1111'
>>> res = dict1['name']
>>> print(res)
王麻子  

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

>>> res = dict1.get('name11111')
>>> print(res)
None
>>> res = dict1.get('name')
>>> print(res)
王麻子

#update一般用来合并字典
#相同的不变,不同的添加

>>> dict1.update(dict2)
>>> print(dict1)
{'name': '张三', 'age': 38, 'phone': 12580, 'high': 160, 'gender': 'man'} 
原文地址:https://www.cnblogs.com/twoo/p/11644159.html