d = {'a':1,'b':2,'c':3} for key, val in d.items(): print(key,val) """ 输出: a 1 b 2 c 3 """ d.items() # dict_items([('a', 1), ('b', 2), ('c', 3)])
下面的写法会报错
1 2 3 4 5 6 7
In [180]: d = {'a':1,'b':2,'c':3}
In [181]: for key, val in d: ...: print(key,val) ...: --------------------------------------------------------------------------- ValueError: not enough values to unpack (expected 2, got 1)
可以这样写,直接遍历所有的键
1 2 3 4 5 6 7
In [180]: d = {'a':1,'b':2,'c':3} In [183]: for key in d: ...: print(key) ...: a b c
In [206]: d = {'a':1,'b':2} # setdefault返回插入的value值 In [207]: r = d.setdefault('c',3) # r: 3 In [208]: r Out[208]: 3 In [209]: d Out[209]: {'a': 1, 'b': 2, 'c': 3} # 已经存在 'c':3 的键值对,所以 setdefault 时 d 无改变 In [210]: r = d.setdefault('c',33) In [211]: r Out[211]: 3 In [212]: d Out[212]: {'a': 1, 'b': 2, 'c': 3}
In [220]: d = {'a':5,'d':7,'c':6} In [224]: sorted(d.items(),key = lambda x:x[1]) Out[224]: [('a', 5), ('c', 6), ('d', 7)]
获取字典最大key的value
1 2 3 4 5 6 7 8 9 10
In [225]: d = {'a':3,'c':1,'b':2} In [226]: max_key = max(d.keys()) In [227]: max_key Out[227]: 'c'
In [228]: d[max_key] Out[228]: 1
In [229]: (max_key,d[max_key]) Out[229]: ('c', 1)
获取字典最大value的key
获取字典最大value的key可能有很多
1 2 3 4 5 6 7
# 获取字典最大value的key可能有很多 In [230]: d = {'a':3,'c':3,'b':2} In [231]: max_val = max(d.values()) In [232]: max_vals = [(key,val) for key,val in d.items() if d[key]==max_val ]
In [294]: {[1,2]} --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-294-4a5722e7ef02> in <module> ----> 1 {[1,2]}
TypeError: unhashable type: 'list'
将可哈希的元祖放入列表中,则不会报错:
1 2
In [295]: {(1,2),(1,2,3),(1,2)} Out[295]: {(1, 2), (1, 2, 3)}
bool类型也是可哈希的数据类型
1 2
In [296]: {True,False,True} Out[296]: {False, True}
字符串也是可哈希的数据类型
1 2 3
In [297]: set1 = {'1','2','1'} In [298]: set1 Out[298]: {'1', '2'}
自定义类的对象也是可哈希的
1 2 3 4 5 6 7 8 9 10 11 12 13
classAnimal: def__init__(self, name): self.name=name defeat(self): print("i love eat !") In [306]: an = Animal('狗') In [307]: set1 = {an} In [308]: an.name='猫'
In [309]: a = set1.pop() In [310]: a.name Out[310]: '猫'