问题描述
我在创建代码时遇到了一个小问题。 我正在尝试在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}
我尝试了很多不同的东西,包括update,defaultdict和其他许多东西,但它们都不起作用。 我不想覆盖任何东西,我只想创建某种嵌套的字典。
关于如何进行的任何想法?
1楼
要合并字典,您可能需要尝试使用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'
}