Roman Holovanov Roman Holovanov - 1 year ago 70
Python Question

Create dictionary from list of lists. Append items to dictionary value if key exist

I have a list like this:

My_dict={0: ['Name1', 'value1', 'value2', 'value3'],
1: ['Name2', 'value4', 'value5', 'value6'],
2: ['Name1', 'value7', 'value8', 'value9']}

and I need to created another dictionary from it - with first value from list as key and for those keys which are duplicated - append values to list of values.
As the result I want to see is:

New_dict= {'Name1': ['value1','value2','value3','value7','value8','value9'],
'Name2': ['value4', 'value5', 'value6']}

Now I'm thinking about turning dictionary into list of lists and creating new dictionary(but I rewrite values when creating new dictionary)

My_dict={0: ['Name1', 'value1', 'value2', 'value3'],
1: ['Name2', 'value4', 'value5', 'value6'],
2: ['Name1', 'value7', 'value8', 'value9']}
for v in My_dict.items():
new_dict={x[0]: x[1:] for x in lists}

Any ideas where should I add if statement for verifying that I'm appending values to existing key in new_dict, not rewriting

Answer Source

You could use collections.defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for key in sorted(My_dict):
...     d[My_dict[key][0]].extend(My_dict[key][1:])
>>> dict(d)
{'Name1': ['value1', 'value2', 'value3', 'value7', 'value8', 'value9'], 'Name2': ['value4', 'value5', 'value6']}

In Python 3.6 and newer you can omit sorted() as dictionaries maintain insertion order since then.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download