Python Forum
List of dictionaries - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: List of dictionaries (/thread-15511.html)



List of dictionaries - bob_for_practice - Jan-20-2019

I've a:
input_list = [{'1':'a'},{'2':'b'},{'3':'c'},{'1':'d'},{'2':'e'},{'4':'f'},{'1':'g'},{'3':'h'}]

I need:
output_list = [{'1':['a','d','g']},{'2':['b','e']},{'3':['c','h']},{'4':['f']}]

Please guide me.


RE: List of dictionaries - buran - Jan-20-2019

what have you tried? post your code in python tags and the full traceback of error you get.


RE: List of dictionaries - DeaD_EyE - Jan-20-2019

Hint: You can use colltections.defaultdict, to append the values to the dict. There is also an example.

Instead of iterating with one loop, you can do a nested loop.
On the top level iterating over this list -> you get dicts
In the second level you iterate over dict.items(), which gives you key, value of the whole dict back.

There is more than one way. I have chosen the way, which needs only 3 lines of understandable code.