<7>python学习笔记——字典

来源:互联网 发布:苏宁物流成本数据分析 编辑:程序博客网 时间:2024/06/05 15:14

字典

dict(mapping) 

dict只有一个参数

字典没有顺序,随机放置。

————常用方法

fromkeys(s[,v])  

创建并返回一个新的字典

参数s是一个键,v是键对应的value,可选。

>>> >>> dict1={}>>> dict1.fromkeys((1,2,3)){1: None, 2: None, 3: None}>>> dict1.fromkeys((1,2,3),'number'){1: 'number', 2: 'number', 3: 'number'}>>> dict1.fromkeys((1,2,3),('one','two','three')){1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}>>> 

fromkeys会把第二个参数整体传递给每一个键。

keys()

返回字典键的引用

>>> dict1=dict1.fromkeys(range(10),'ok')>>> dict1{0: 'ok', 1: 'ok', 2: 'ok', 3: 'ok', 4: 'ok', 5: 'ok', 6: 'ok', 7: 'ok', 8: 'ok', 9: 'ok'}>>> for eachkey in dict1.keys():...     print(eachkey)... 0123456789>>> 

返回全部key
values()

返回字典值的引用

items()

返回字典的每一个键值对,用元组的方式返回每一对。

get()

使用get()方法,获取键对应的值

>>> dict1.get(9)'ok'>>> dict1.get(10)>>> print(dict1.get(10))None>>> 
clear()

清空整个字典。

pop()

删除一个指定键,返回该键对应的值

popitem()
随机返回一对键值对

>>> a{1: 'a', 3: 'c', 4: 'd'}>>> a.popitem()(1, 'a')>>> a{3: 'c', 4: 'd'}>>> 

setdefault()

与get()类似,但是在字典中找不到键的时候会自动添加。可以用来添加键值对

>>> a{3: 'c', 4: 'd'}>>> a.setdefault('OK')>>> a{'OK': None, 3: 'c', 4: 'd'}>>> a.setdefault(5,'longsi')'longsi'>>> a{3: 'c', 4: 'd', 5: 'longsi', 'OK': None}>>> 

update()

通过一个字典的映射关系去更新另外一个字典

>>> a{3: 'c', 4: 'd', 5: 'longsi', 'OK': None}>>> b = {'OK':'Dog'}>>> a.update(b)>>> a{3: 'c', 4: 'd', 5: 'longsi', 'OK': 'Dog'}>>> 













0 0