您只需要相信我,这就是我正在发生的事情,它使我发疯
基本上,在Jupyter Notebook中进行了一系列操作之后,我得到了如下的字典
dict1 = {'Cash': [], 'Current Liabilities': ['overpayment','loan'],'Debt': ['debt1', 'debt2'],
'Dividends Declared': [],'Fixed Assets': [] }
我的目标是将dict1与dict2合并以在下面生成merge_dict
dict2 = {'Cash': ['USD', 'CAD'], 'Debt': 'debt3'}
merge_dict = {'Cash': ['USD', 'CAD'], 'Current Liabilities': ['overpayment','loan'],'Debt': ['debt1', 'debt2', 'debt3'], 'Dividends Declared': [],'Fixed Assets': [] }
我使用以下代码成功合并了dict1和dict2:
for k,v in dict1.items():
for u, i in dict2.items():
if k == u:
if type(i) is list:
[v.append(e) for e in i]
else:
v.append(i)
让我发疯的是,我在Jupyter Notebook中获得的字典对象(在本文中称为dict1)与dict1完全一样,但是由于某些原因,产生的输出是这样的:
merge_dict = {'Cash': ['USD', 'CAD'], 'Current Liabilities': ['overpayment','loan'],'Debt': ['debt1', 'debt2', 'debt3'], 'Dividends Declared': ['USD', 'CAD'],'Fixed Assets': ['USD', 'CAD']}
我不明白为什么“申明股息”和“固定资产”也附加了元素,尽管它们与dict2的键不同。我得到的dict对象可能有什么问题,使它的行为与dict1不同?
答案 0 :(得分:0)
要通过键合并2个字典并累积值:
from collections import defaultdict
dict1 = {'Cash': [], 'Current Liabilities': ['overpayment', 'loan'], 'Debt': ['debt1', 'debt2'],
'Dividends Declared': [], 'Fixed Assets': []}
dict2 = {'Cash': ['USD', 'CAD'], 'Debt': 'debt3'}
res = defaultdict(list)
for k in set(dict1) | set(dict2): # Union of dict keys
v1 = dict1.get(k, [])
v2 = dict2.get(k, [])
res[k].extend(v1 if isinstance(v1, list) else [v1])
res[k].extend(v2 if isinstance(v2, list) else [v2])
print(dict(res))
输出:
{'Cash': ['USD', 'CAD'], 'Fixed Assets': [], 'Current Liabilities': ['overpayment', 'loan'], 'Dividends Declared': [], 'Debt': ['debt1', 'debt2', 'debt3']}
答案 1 :(得分:0)
按照您的方法,请找到以下代码:
for k,v in dict1.items():
for u,i in dict2.items():
if k==u:
if type(i) is list:
dict1[k].extend(i) # list is extending in list value of dict
else:
dict1[k].append(i) # elem is appending in list
print(dict1)
Output:
{'Cash': ['USD', 'CAD'], 'Current Liabilities': ['overpayment', 'loan'], 'Debt': ['debt1', 'debt2', 'debt3'], 'Dividends Declared': [], 'Fixed Assets': []}
希望这会有所帮助!