创建代码时遇到一个小问题。我试图在Python中合并两个字典。他们每个人都有一组键,让我们说:
a={person_id:xx, address_id: xx, name:xx}
b={address_id:xx, street:xx, postcode:xx, town:xx}
他们每个人都有很多条目,我的意思是他们看起来像:
a={person_id:1. address_id:20, name:john; person_id:2, address_id:200,
name: mary';... and 10000 more entries like that}
b={address_id:20... same situation like in a}
我想得到:
merged_dic={person_id:xx, address_id {street:xx, postcode:xx, town:xx}, name:xx; person_id:xxx.. and so on}
我尝试了很多不同的东西,更新,defaultdict和更多,但没有一个工作。我不想覆盖一些东西,我只是想创建一些嵌套的dict。
关于如何进行的任何想法?
答案 0 :(得分:3)
要合并字典,您可能需要尝试dict.update()
方法,例如:
def merge_my_dicts(a_dict, b_dict):
# verify the addresses match
assert b_dict['address_id'] == a_dict['address_id']
# get a copy of the address dict and remove extra
address = b_dict.copy()
del address['address_id']
# get a copy of the main dict, and update with the address
new_dict = a_dict.copy()
new_dict.update({'address_id': address})
return new_dict
a = {'person_id': 'pid', 'address_id': 'aid', 'name': 'nm'}
b = {'address_id': 'aid', 'street': 'st', 'postcode': 'pc', 'town': 'tn'}
print(merge_my_dicts(a, b))
{
'person_id': 'pid',
'address_id': {
'street': 'st',
'postcode': 'pc',
'town': 'tn'},
'name': 'nm'
}