Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping Python dictionary keys as a list and create a new dictionary with this list as a value

I have a python dictionary

d = {1: 6, 2: 1, 3: 1, 4: 9, 5: 9, 6: 1}

Since the values in the above dictionary are not unique, I want to group the all the keys of unique values as a list and create a new dictionary as follows:

v = {6:[1], 1:[2, 3, 6], 9: [4, 5]}

Note the keys of new dictionary v should be sorted. I am finding it hard to visualize and implement this dictionary creation.

like image 733
Shankar Avatar asked Apr 01 '13 21:04

Shankar


People also ask

How do you group a dictionary in a list Python?

Group List of Dictionary Data by Particular Key in Python can be done using itertools. groupby() method.

How do you create a dictionary from a list of keys and values?

Using zip() with dict() function The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip() function with a dictionary constructor.

How do you group dictionary using keys?

Method : Using sorted() + items() + defaultdict() The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().

Can you use a list as a key for a dictionary Python?

We can use integer, string, tuples as dictionary keys but cannot use list as a key of it .


2 Answers

Using collections.defaultdict for ease:

from collections import defaultdict

v = defaultdict(list)

for key, value in sorted(d.items()):
    v[value].append(key)

but you can do it with a bog-standard dict too, using dict.setdefault():

v = {}

for key, value in sorted(d.items()):
    v.setdefault(value, []).append(key)

The above sorts keys first; sorting the values of the output dictionary later is much more cumbersome and inefficient.

If anyone would not need the output to be sorted, you can drop the sorted() call, and use sets (the keys in the input dictionary are guaranteed to be unique, so no information is lost):

v = {}

for key, value in d.items():
    v.setdefault(value, set()).add(key)

to produce:

{6: {1}, 1: {2, 3, 6}, 9: {4, 5}}

(that the output of the set values is sorted is a coincidence, a side-effect of how hash values for integers are implemented; sets are unordered structures).

like image 184
Martijn Pieters Avatar answered Oct 16 '22 08:10

Martijn Pieters


If you don't actually need a dict at the end of the day, you could use itertools.groupby:

from itertools import groupby
from operator import itemgetter

for k, v in groupby(sorted(d.items(), key=itemgetter(1)), itemgetter(1)):
    print(k, list(map(itemgetter(0), v)))

Of course, you could use this to construct a dict if you really wanted to:

{
    k: list(map(itemgetter(0), v))
    for k, v in groupby(sorted(d.items(), key=itemgetter(1)), itemgetter(1))
}

But at that point, you're probably better off using Martijn's defaultdict solution.

like image 26
mgilson Avatar answered Oct 16 '22 10:10

mgilson