python 把一个字典key的值加到另一个字典的key的值中?
发布网友
发布时间:2022-04-07 08:54
我来回答
共2个回答
热心网友
时间:2022-04-07 10:23
import openpyxl
a = {'A': [2136, 1888, 2102, 1911, 1966], 'B': [123, 698, 2564]}
b = {'A': [2136, 1695, 2102, 1888]}
for key in a.keys():
for bkey in b.keys():
if bkey == key:
for i in b[bkey]:
a[key].append(i)
print(a)
格式如上,注意对齐
热心网友
时间:2022-04-07 11:41
A = 'A'
B = 'B'
d1 = {A: [2136, 1888, 2102, 1911, 1966], B: [123, 698, 2564]}
d2 = {A: [2136, 1695, 2102, 1888]}
from collections import defaultdict
d3 = defaultdict(list)
for d in [d1, d2]:
for k in d.keys():
d3[k].extend(d[k])
print(d3)
#defaultdict(<class 'list'>, {'A': [2136, 1888, 2102, 1911, 1966, 2136, 1695, 2102, 1888], 'B': [123, 698, 2564]})