python - dict.update overwrites existing keys, how to avoid? -
python - dict.update overwrites existing keys, how to avoid? -
when using update function dictionary in python merging 2 dictionaries , 2 dictionaries have same keys apparently beingness overwritten.
a simple example:
simple_dict_one = {'name': "tom", 'age': 20} simple_dict_two = {'name': "lisa", 'age': 17} simple_dict_one.update(simple_dict_two)
after dicts merged next dict remains:
{'age': 17, 'name': 'lisa'}
so if have same key in both dict 1 remains (the lastly 1 apparently). if have lot of names several sources want temp dict each of , want add together whole bigger dict.
is there way merge 2 dicts , still maintain keys ? guess suppose have 1 unique key how merge 2 dicts without loosing data
well have several sources gather info from, illustration ldap database , other sources have python functions create temp dict each want finish dict @ end sort of concatenates or displays info gathered sources.. have 1 dict holding info
what trying 'merging' not quite ideal. said yourself
i guess suppose have 1 unique key
which makes relatively , unnecessarily hard gather info in 1 dict. do, instead of calling .update()
on existing dict, add together sub-dict. key name of source gathered information. value dict receive source, , if need store more 1 dict of same source can store them in list.
example
>>> info = {} >>> person_1 = {'name': 'lisa', 'age': 17} >>> person_2 = {'name': 'tom', 'age': 20} >>> data['people'] = [person_1, person_2] >>> info {'people': [{'age': 17, 'name': 'lisa'}, {'age': 20, 'name': 'tom'}]}
then whenever need add together newly gathered information, add together new entry data
dict
>>> ldap_data = {'foo': 1, 'bar': 'baz'} # dummy info >>> data['ldap_data'] = ldap_data >>> info {'people': [{'age': 17, 'name': 'lisa'}, {'age': 20, 'name': 'tom'}], 'ldap_data': {'foo': 1, 'bar': 'baz'}}
the source-specific info extractable data
dict
>>> data['people'] [{'age': 17, 'name': 'lisa'}, {'age': 20, 'name': 'tom'}] >>> data['ldap_data'] {'foo': 1, 'bar': 'baz'}
python dictionary
Comments
Post a Comment