Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List of dictionaries
#1
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.
Reply
#2
what have you tried? post your code in python tags and the full traceback of error you get.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 1 488 Oct-27-2023, 03:03 PM
Last Post: buran
  Access list of dictionaries britesc 4 1,069 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  function that returns a list of dictionaries nostradamus64 2 1,746 May-06-2021, 09:58 PM
Last Post: nostradamus64
  convert List with dictionaries to a single dictionary iamaghost 3 2,858 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,271 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  Help accessing elements of list of dictionaries Milfredo 6 2,836 Sep-07-2020, 01:32 AM
Last Post: Milfredo
  Accessing values in list of dictionaries pythonnewbie138 2 2,129 Aug-02-2020, 05:02 PM
Last Post: pythonnewbie138
  how does .join work with list and dictionaries gr3yali3n 7 3,289 Jul-07-2020, 09:36 PM
Last Post: bowlofred
  creating a list of dictionaries from API calls AndrewEnglsh101 5 3,063 Apr-03-2020, 02:21 PM
Last Post: AndrewEnglsh101
  List of dictionaries: use key-value instead of index? dn237 6 3,884 Jun-03-2019, 05:52 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020