dict
key-value键值对的数据的集合;
可变的;
无序的;
key不重复,key用来作唯一标识,key要为hashable(不可变类型),key的要求和set的元素要求一致;
k,v一起称为item,d.popitem()弹出的二元组也称item;
d.items(),在python3中叫dictionary view,如for i in d.items();
dict定义、初始化:
d = dict()
d = {}
dict(*kwargs),使用name=value对初始化一个字典;
dict(iterable,**kwargs),使用可迭代对象和name=value对构造字典,不过可迭代对象的元素必须是一个二元结构;
dict(mapping,**kwargs),使用一个字典构造另一个字典;
类方法,dict.fromkeys(iterable,value),如d=dict.fromkeys(range(5),0),0为缺省值;
例:
In [1]: d=dict(((1,'a'),(2,'b')))
In [2]: d
Out[2]: {1: 'a', 2: 'b'}
In [3]: d=dict(([1,'a'],[2,'b']))
In [4]: d
Out[4]: {1: 'a', 2: 'b'}
In [5]: d=dict(a=5,b=6,z=[1,2,3])
In [6]: d
Out[6]: {'a': 5, 'b': 6, 'z': [1, 2, 3]}
In [7]: d=dict(a=5,b=6,1=2) #1=2有歧义,此处即变量名=value,是非法的标识符
File "<ipython-input-7-8a208196f03e>", line 1
d=dict(a=5,b=6,1=2) ^
SyntaxError: keyword can't be an expression
In [8]: d={'a':10,'b':20,'c':None,'d':[1,2,3]}
In [9]: d
Out[9]: {'a': 10, 'b': 20, 'c': None, 'd': [1, 2, 3]}
In [10]: d=dict.fromkeys(range(5)) #value未定义为None
In [11]: d
Out[11]: {0: None, 1: None, 2: None, 3: None, 4: None}
In [12]: d=dict.fromkeys(range(5),0)
In [13]: d
Out[13]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
In [14]: l1=list(range(5))
In [15]: e = enumerate(l1) #返回可迭代对象
In [16]: e
Out[16]: <enumerate at 0x7f634c2c4678>
In [17]: for i in e:
...: print(i) #返回二元组
...:
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
In [19]: e=enumerate(l1)
In [20]: d=dict(e)
In [21]: d
Out[21]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
In [22]: d={('a',1)} #{}里是单个对象,此例为二元组,该类型为set;
In [23]: d
Out[23]: {('a', 1)}
In [24]: type(d)
Out[24]: set
In [25]: d=dict((('a',1),)) #dict()里要是iterable object,注意逗号,单个二元组不是可迭代对象
In [26]: d
Out[26]: {'a': 1}
In [27]: d=dict(('a',1),)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-27-671890814fce> in <module>()
----> 1 d=dict(('a',1),)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
In [28]: d=dict((('a',1)))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-927d7fa29131> in <module>()
----> 1 d=dict((('a',1)))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
In [30]: d=dict.fromkeys(range(1,5),(1,)) #(1,)为value的缺省值
In [31]: d
Out[31]: {1: (1,), 2: (1,), 3: (1,), 4: (1,)}
In [32]: d=dict.fromkeys(range(1,5),[1,2])
In [33]: d
Out[33]: {1: [1, 2], 2: [1, 2], 3: [1, 2], 4: [1, 2]}
In [34]: d[4].append(3) #注意引用类型,会全部变
In [35]: d
Out[35]: {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3], 4: [1, 2, 3]}
dict元素的访问:
d[key],返回key对应的value,key不存在抛KeyError异常;
get(key[,default]),返回key对应的value,key不存在返回缺省值,如果没有设置缺省值就返回None;
setdefault(key[,default]),返回key对应的value,key不存在添加kv时,value为default,并返回default,如果default没有设置,缺省为None;当不确定某key的value是否存在用setdefault();
例:
In [47]: d=dict(([(1,3,4),(2,5,8,9)],)) #(1,3,4)为key,(2,5,8,9)为value
In [48]: d
Out[48]: {(1, 3, 4): (2, 5, 8, 9)}
In [49]: d[(1,3,4)]
Out[49]: (2, 5, 8, 9)
In [50]: f=d.get((1,3,4))
In [51]: f
Out[51]: (2, 5, 8, 9)
In [52]: f=d.get((1,4,3))
In [53]: f
In [54]: type(f)
Out[54]: NoneType
In [55]: d.get(1,50)
Out[55]: 50
In [56]: d.get((1,3,4),50)
Out[56]: (2, 5, 8, 9)
In [57]: d.setdefault(3)
In [58]: d
Out[58]: {(1, 3, 4): (2, 5, 8, 9), 3: None}
In [66]: f=d.setdefault(4,400)
In [67]: f
Out[67]: 400
In [68]: f=d.setdefault(4,401)
In [69]: f
Out[69]: 400
dict增加修改:
d[key]=value,将key对应的value改为value;key不存在,添加新的kv对;
update([other])-->None,使用另一个字典的kv时更新本字典,key不存在就添加,key存在覆盖已存在的key对应的value,就地修改;
例:
In [36]: d={}
In [37]: type(d)
Out[37]: dict
In [38]: d.update(red=1)
In [39]: d
Out[39]: {'red': 1}
In [40]: d.update((('red',2),))
In [41]: d
Out[41]: {'red': 2}
In [42]: d.update({'red':3})
In [43]: d
Out[43]: {'red': 3}
In [75]: del d
In [76]: d=dict(a=1,b=2)
In [77]: d
Out[77]: {'a': 1, 'b': 2}
In [78]: d['c']=3 #没有则创建
In [79]: d
Out[79]: {'a': 1, 'b': 2, 'c': 3}
In [80]: d['c']=8 #有则修改
In [81]: d
Out[81]: {'a': 1, 'b': 2, 'c': 8}
In [82]: d2=dict(red=3)
In [83]: d2
Out[83]: {'red': 3}
In [84]: d.update(d2,red=8) #关键字参数,red=1要放到最后
In [85]: d
Out[85]: {'a': 1, 'b': 2, 'c': 8, 'red': 8}
dict删除:
pop(key[,default]),key存在,移除它,并返回它的value;key不存在,返回给定的default;default未设置,key不存在时抛KeyError异常;
popitem(),移除并返回一个任意的kv对,字典为empty抛KeyError异常,k,v一起称为item,popitem()弹出的二元组也称item;
clear(),清空字典;
注意,不能用for loop一边迭代一边删元素,用while可以对比长度;
del语句;
例:
In [86]: d=dict.fromkeys(range(5),[1,2,3])
In [87]: d
Out[87]: {0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3], 4: [1, 2, 3]}
In [88]: f=d.pop(4)
In [89]: f
Out[89]: [1, 2, 3]
In [90]: d
Out[90]: {0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
In [91]: f.append(4) #注意引用类型
In [92]: d
Out[92]: {0: [1, 2, 3, 4], 1: [1, 2, 3, 4], 2: [1, 2, 3, 4], 3: [1, 2, 3, 4]}
In [93]: d.popitem()
Out[93]: (0, [1, 2, 3, 4])
In [94]: d.popitem()
Out[94]: (1, [1, 2, 3, 4])
In [95]: d.popitem()
Out[95]: (2, [1, 2, 3, 4])
In [96]: d.popitem()
Out[96]: (3, [1, 2, 3, 4])
In [97]: d.popitem()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-97-83c64cff336b> in <module>()
----> 1 d.popitem()
KeyError: 'popitem(): dictionary is empty'
字典遍历:
遍历key:
for k in d:
print(k)
for k in d.keys():
print(k)
遍历value:
for k in d:
print(d[k])
for k in d.keys():
print(d.get(k))
for v in d.values():
print(v)
遍历item,kv对:
for item in d.items():
print(item) #返回(k,v)的二元组
for k,v in d.items():
print(k,v)
总结:
python3中,d.keys(),d.values(),d.items()方法返回一个类似生成器的可迭代对象,不会把函数的返回结果复制到内存中;
python2中,d.keys(),d.values(),d.items()会返回一个新的列表,占据新的内存空间,所以python2建议使用d.iterkeys(),d.itervalues(),d.iteritems()版本,返回一个迭代器而不是一个copy;
for k,_ in d.items(): #解构
print(k)
defaultdict:
collections.defaultdict([default_factory[,...]])
default_factory,缺省是None,它提供一个初始化函数,当key不存在的时候,会调用这个工厂函数来生成key对应的value;
例:
from collections import defaultdict
d1 = {}
d2 = defaultdict(list) #l1=list(),高阶函数
for k in 'abcde':
for v in range(5):
if k not in d1.keys():
d1[k] = []
d1[k].append(v)
print(d1)
for k in 'mnopq':
for v in range(3):
d2[k].append(v)
print(d2)
OrderedDict,有序字典:
可记录元素插入的顺序(按加入的顺序放),打印时也是按这个顺序输出打印(不是hash值排序的结果);
3.6版本的python dict按加入顺序记录了key,是按记录key插入的顺序;
collections.OrderedDict([items])
key并不是按照加入的顺序排列,可使用OrderedDict记录顺序;
例:
from collections import OrderedDict
import random
d = {'banana':3,'apple':4,'pear':1,'orange':2}
print(d)
keys = list(d.keys())
random.shuffle(keys)
print(keys)
od = OrderedDict()
for k in keys:
od[k] = d[k] #往od字典里添kv对
print(od,od.keys())
用户输入一个数字,打印每一位数字及其重复的次数?
例:
import random
nums = [random.randint(0,9) for _ in range(5)] #[chr(random.randint(48,57)) for _ in range(5)]
print(nums)
nums_dict = {}
for i in nums:
nums_dict[i] = nums_dict.get(i,0) + 1
print(nums_dict)
例:
import random
words = [random.randint(0,9) for _ in range(10)]
print(words)
words_count = {}
for k,v in zip(words,(1,)*len(words)):
words_count[k] = words_count.get(k,0) + 1
lst = sorted(words_count.items(),key=lambda x:x[1],reverse=True)
print(lst)
for i in range(3):
print(str(lst[i]).strip("()"))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。