Python Forum
Python list - group by dict key
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python list - group by dict key
#1
Pls help me on this python list with dict items query.

I need to group these elements by name key.

Input:
[{'name': 'charlie', 'Ready For Dev': 2.0}, {'name': 'charlie', 'Ready for Release': 12.0},
{'name': 'john', 'Ready to Test': 2.0},
{'name': 'henry', 'Open': 8.0}, {'name': 'henry', 'Ready for Release': 16.0}]

Expected Output:
[{'name': 'charlie', 'Ready For Dev': 2.0, 'Ready for Release': 12.0},
{'name': 'john', 'Ready to Test': 2.0},
{'name': 'henry', 'Open': 8.0, 'Ready for Release': 16.0}]


I have tried like below so far, but not getting my expected output.

temp=[{'name': 'charlie', 'Ready For Dev': 2.0},
 {'name': 'charlie', 'Ready for Release': 12.0},
 {'name': 'john', 'Ready to Test': 2.0},
 {'name': 'henry', 'Open': 8.0},
 {'name': 'henry', 'Ready for Release': 16.0}
 ]

names = ['charlie', 'john', 'henry']

for name in names:
    x=[]
    for item in temp:

        if item['name']==name:
            x.append(item)
            print (x)
Reply
#2
Plan: 'get names, for every name get all dictionaries which have this name, chain them together and append to list'

This takes advantage on collections.ChainMap which as name suggest chains mappings and fact that dictionary keys must be unique


from collections import ChainMap

records = [{'name': 'charlie', 'Ready For Dev': 2.0},
           {'name': 'charlie', 'Ready for Release': 12.0},
           {'name': 'john', 'Ready to Test': 2.0},
           {'name': 'henry', 'Open': 8.0},
           {'name': 'henry', 'Ready for Release': 16.0}]

names = {row['name'] for row in records}     # set of unique names 

new = []                                     # list to collect new dictionaries

for name in names:
    new.append(dict(ChainMap(*(row for row in records if row['name'] == name)))
Value of 'new' will be:

Output:
[{'name': 'henry', 'Ready for Release': 16.0, 'Open': 8.0}, {'name': 'john', 'Ready to Test': 2.0}, {'name': 'charlie', 'Ready for Release': 12.0, 'Ready For Dev': 2.0}]
One can express for-loop with oneliner:

[dict(ChainMap(*(row for row in records if row['name'] == name))) for name in names]  
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
you can use defaultdict

temp=[{'name': 'charlie', 'Ready For Dev': 2.0},
 {'name': 'charlie', 'Ready for Release': 12.0},
 {'name': 'john', 'Ready to Test': 2.0},
 {'name': 'henry', 'Open': 8.0},
 {'name': 'henry', 'Ready for Release': 16.0}
 ]

from collections import defaultdict
combined = defaultdict(dict)

for item in temp:
    combined[item['name']].update(item)

print(list(combined.values()))
Output:
[{'name': 'charlie', 'Ready For Dev': 2.0, 'Ready for Release': 12.0}, {'name': 'john', 'Ready to Test': 2.0}, {'name': 'henry', 'Open': 8.0, 'Ready for Release': 16.0}]
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


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 170 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 1,199 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  group by create pivot table python dawid294 1 1,275 Jun-22-2022, 06:13 PM
Last Post: Larz60+
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 1,445 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Updating nested dict list keys tbaror 2 1,270 Feb-09-2022, 09:37 AM
Last Post: tbaror
  What type of *data* is the name of a list/tuple/dict, etc? alloydog 9 4,349 Jan-30-2021, 07:11 AM
Last Post: alloydog
  Group List Elements according to the Input with the order of binary combination quest_ 19 6,390 Jan-28-2021, 03:36 AM
Last Post: bowlofred
Question dict value, how to change type from int to list? swissjoker 3 2,724 Dec-09-2020, 09:50 AM
Last Post: perfringo
  How to remove dict from a list? Denial 7 2,904 Sep-28-2020, 02:40 PM
Last Post: perfringo
  Trouble with converting list , dict to int values! faryad13 7 3,722 Sep-04-2020, 06:25 AM
Last Post: faryad13

Forum Jump:

User Panel Messages

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