我有两本字典。
Dict1={'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
Dict2={'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}
我想从Dict1中获取所有键值对,并在第二个字典中查找相应的股票价格。然后我想在第一个字典中添加股票价格数据。你能用python帮我解决这个问题吗?
我想要的输出是:
Dict3={'comp1':{'Company name':'aaa','Industry':'aaa','Stock price':100},'comp2':{'Company name':'bbb','Industry':'bbb','Stock price':200}}
对于python 3.9+,您可以使用|
:
Dict1 = {'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
Dict2 = {'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}
output = {k: d | Dict2[k] for k, d in Dict1.items()}
print(output)
# {'comp1': {'Company name': 'aaa', 'Industry': 'aaa', 'Stock price': 100}, 'comp2': {'Company name': 'bbb', 'Industry': 'bbb', 'Stock price': 200}}
对于3.9之前的python版本(但仍然是3.5+),
output = {k: {**d, **Dict2[k]} for k, d in Dict1.items()}
如果你碰巧有python <3.5,则可以使用:
output = {k: d.copy() for k, d in Dict1.items()} # or, copy.deepcopy(Dict1)
for k, d in output.items():
d.update(Dict2[k])
如果您对Dict1
的就地修改感到满意,那么您不需要复制(第一行)。
清空
dict1 = {'comp1':{'Company name':'aaa','Industry':'aaa'},'comp2':{'Company name':'bbb','Industry':'bbb'}}
dict2 = {'comp2':{'Stock price':200},'comp3':{'Stock price':300},'comp1':{'Stock price':100},'comp4':{'Stock price':400}}
dict3 = {}
for k in dict1.keys():
dict3[k]= {'Company name': dict1[k]['Company name'], 'Industry': dict1[k]['Industry'], 'Stock price': dict2[k]['Stock price']}