-1

Considering a dictionary with several recurring values. How to group the dictionary by value? For example:

mydict = 
{
    'germany': 'europe', 
    'france': 'europe',
    'canada': 'north america', 
    'latvia': 'europe'
    'usa': 'north america',
    'china': 'asia'
}

Group by value into list.

groupdDict =
{
    'europe': ['germany','france','latvia'],
    'north america': ['canada','usa'],
    'asia': ['china']
}
DougKruger
  • 4,424
  • 14
  • 41
  • 62

1 Answers1

2

Using collections.defaultdict

Demo:

mydict ={
        'germany': 'europe',
        'france': 'europe',
        'canada': 'north america',
        'latvia': 'europe',
        'usa': 'north america',
        'china': 'asia'
    }

import collections
d = collections.defaultdict(list)
for k,v in mydict.items():
    d[v].append(k)
print(d)

Or using a simple Iteration

Demo:

d = {}
for k,v in mydict.items():
    if v not in d:
        d[v] = []
    d[v].append(k)
print(d)

Output:

{'north america': ['canada', 'usa'], 'europe': ['france', 'latvia', 'germany'], 'asia': ['china']}
Rakesh
  • 81,458
  • 17
  • 76
  • 113