python字典合并, 列表生成字典
可能会用到的方法
一 字典
dic1 = {'a': 2, 'b': 3, 'c': 4, 'd': 3}
dic2 = {'a': 1, 'c': 4, 'f': 3}
dic3 = {'a': 5, 'g': 6, 'c': 1}
dic4 = {'33': [438, 62, 471],
'304': [74],
'307': [368, 304, 439, 74, 62],
'75': [74, 368]
}
dic5 = {'33': [438, 368],
'34': [56, 89],
'75': [74]}
- 对dic1和dic2, 保留 dic1的key, 如果dic2包含dic1中的key, 则替换成dic2的value,如果不包含,则将dic1中的value修改为0
temp = {}
for k, v in dic1.items():
if k in dic2.keys():
temp[k] = dic2[k]
else:
temp[k] = 0
结果: {'a': 1, 'b': 0, 'c': 4, 'd': 0}
- 对dic1, dic2, dic3, 保留dic1的key, 如果dic1中的key在dic2和dic3中,则value值相加,否则保留dic1中的value
方案1:
temp_1 = {}
for k, v in dic1.items():
if k in dic2.keys() | dic3.keys():
temp_1[k] = dic1[k] + dic2[k] + dic3[k]
else:
temp_1[k] = dic1[k]
结果: {'a': 8, 'b': 3, 'c': 9, 'd': 3}
方案2:可以是多个字典
from functools import reduce
def sum_dict_1(a,b):
temp = dict()
for key in a.keys():
if key in b.keys():
temp[key] = sum([a.get(key, 0) for a in (a, b)])
else:
temp[key] = a[key]
return temp
print(reduce(sum_dict_1, [dic1, dic2, dic3]))
结果: {'a': 8, 'b': 3, 'c': 9, 'd': 3}
3.合并dic1, dic2, key值相同,value值相加
from functools import reduce
def sum_dict(a,b):
temp = dict()
for key in a.keys()| b.keys():
temp[key] = sum([d.get(key, 0) for d in (a, b)])
return temp
sum_dict(dic1, dic2)
结果: {'d': 3, 'b': 3, 'f': 3, 'a': 3, 'c': 8}
- 对dic3, dic4合并,合并dic3和dic4中的key, value
def merge_dic(dic1, dic2):
result = {}
for k, v in dic1.items():
for kk, vv in dic2.items():
if k == kk:
result[k] = list(set(list(chain(*[v, vv]))))
if k not in dic2.keys():
result[k] = v
for kk, vv in dic2.items():
if kk not in dic1.keys():
result[kk] = vv
return result
结果:
{'33': [62, 368, 438, 471],
'304': [74],
'307': [368, 304, 439, 74, 62],
'75': [368, 74],
'34': [56, 89]}
二 列表生成字典
li =[1, 5, 33,5, 6]
li_1 = ['a', 'b', 'c', 'a', 'c']
dd = {}
for i, key in enumerate(li_1):
if not dd.get(key):
dd[key] = [li[i]]
else:
dd[key].append(li[i])
print(dd)
结果: {'a': [1, 5], 'b': [5], 'c': [33, 6]}
三 获取字典中的值最大的前n项
from collections import Counter
def get_order_dict_N(_dict, N):
# 获取字典中值最大的前n个数,并包含并列情况
result = Counter(_dict).most_common(N)
d = {}
for k,v in result:
d[k] = v
return d
a = {'a':9,'b':1,'c':5,'d':9}
get_order_dict_N(a, 2)
结果: {'a': 9, 'd': 9}
四 对字典排序
a = {'a':9,'b':1,'c':5,'d':10}
# 对字典进行排序
L = sorted(a.items(),key=lambda item:item[1],reverse=True)