使用collections库中的defaultdict会使方法更加简单和清晰易懂
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(3)
print(d)# defaultdict(, {'a': [1, 2], 'b': [3]})
创建一个一键多值的字典其实并不难,但是想要初始化,推荐如下方法:
from collections import defaultdict
d = defaultdict(list)
pairs = [('a',3),('a',5),('b',6)]
for key, val in pairs:
d[key].append(val)
print(d)#defaultdict(, {'a': [3, 5], 'b': [6]})
prices = {
'ACME':45.23,
'AAPL':123.33
'HP':20.21
'LLEN':90.21
}
minPri = min(zip(prices.values(),prices.keys()))
maxPri = max(zip(prices.values(),prices.keys()))
priSort = sorted(zip(prices.values(),prices.keys()))
#zip()创建的是一个迭代器...
#求出最大值的键和值
print(max(prices,key = lambda k:prices[key]))#键
print(prices[max(prices,key = lambda k:prices[key])])#值
dict1 = {
'1':2,'3':7,'6':20}
dict2 = {
'1':2,'3':3,'12':100}
print(dict1.keys() & dict2.keys())#两个字典中重复的键
print(dict1.keys() - dict2.keys())#找到在dict1中却不在dict2中的键
print(dict1.items() & dict2.items())#找到完全相同的键值对
睡了睡了…困…
未完待续,佛系养生