python字典
python里面的字典是无序的,key:value成对,key是唯一的且不可变的,value可以是任意类型,字典跟列表一样具有增删改查的方法
1.创建字典
>>> dict_lst = {'abc':123,"edf":456}
>>> dict_lst2 = {}
>>> dict_lst3=dict()
>>> print(dict_lst2,dict_lst3)
{} {}
>>>
2.访问字典里面的值
通过key直接访问
>>> dict_lst = {'abc':123,"edf":456}
>>> dict_lst['abc']
123
3.修改字典
修改字典如果key不存在则新增,如果存在在修改key对应的value的内容
>>> dict_lst = {'abc':123,"edf":456}
>>> dict_lst['abc']=789
>>> dict_lst
{'abc': 789, 'edf': 456}
>>> dict_lst['xyz'] = 123
>>> dict_lst
{'abc': 789, 'edf': 456, 'xyz': 123}
>>>
4.删除字典
可以删除指定key,也可以清空整个字典的key-value,还可以删除整个字典
{'abc': 789, 'edf': 456, 'xyz': 123}
>>> del dict_lst['abc']
>>> dict_lst
{'edf': 456, 'xyz': 123}
>>> dict_lst.clear()
>>> dict_lst
{}
>>> del dict_lst
>>> dict_lst
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
dict_lst
NameError: name 'dict_lst' is not defined
>>>
5.字典内置函数
len(dict)返回字典长度,str(dict)把字典转换成字符串
>>> dict_lst = {'abc':123,"edf":456}
>>> len(dict_lst)
2
>>> str(dict_lst)
"{'abc': 123, 'edf': 456}"
>>>
6.字典内置方法
>>> dict_lst.clear()
>>> dict_lst = {'abc':123,"edf":456}
>>> dict_lst2 = dict_lst.copy()
>>> dict_lst2
{'abc': 123, 'edf': 456}
>>> dict.fromkeys([1,2,3])
{1: None, 2: None, 3: None}
>>> dict.fromkeys([1,2,3],'abc')
{1: 'abc', 2: 'abc', 3: 'abc'}
>>> dict_lst2.get('abc')
123
>>> 'abc' in dict_lst2
True
>>> dict_lst.items()
dict_items([('abc', 123), ('edf', 456)])
>>> dict_lst
{'abc': 123, 'edf': 456}
>>> dict_lst.keys()
dict_keys(['abc', 'edf'])
>>> dict_lst.values()
dict_values([123, 456])
>>> dict_lst.setdefault("edf")
456
>>> dict_lst.setdefault("xyz")
>>> dict_lst
{'abc': 123, 'edf': 456, 'xyz': None}
>>> dict_lst2
{'abc': 123, 'edf': 456}
>>> dict_lst.update(dict_lst2)
>>> dict_lst
{'abc': 123, 'edf': 456, 'xyz': None}
>>> dict_lst.pop('abc')
123
>>> dict_lst
{'edf': 456, 'xyz': None}
>>> dict_lst.popitem()
('xyz', None)
>>> dict_lst
{'edf': 456}
>>>
|