Home > Back-end >  how to reverse a dictionary in python and create a list out of the duplicate keys value
how to reverse a dictionary in python and create a list out of the duplicate keys value

Time:12-13

I gave myself a task today, just trying to figure out the exercise below in python


# given the dictionary below

dic = {
  "jane": "doe",
  "remy": "ma",
  "haaland": "buuk",
  "adam": "doe",
}

new_dict = {}

for x, y in dic.items():
  if y not in new_dict.keys(): 
    new_dict[y] = x
  else:
    new_dict[y] = [x]

print("results: ", new_dict)

# results:  {'doe': ['adam'], 'ma': 'remy', 'buuk': 'haaland'}

how can i rather achieve the following result?

=> results:  {'doe': ['jane', 'adam'], 'ma': 'remy', 'buuk': 'haaland'}

Thank you for the help

CodePudding user response:

The most straightforward solution would be:

from collections import defaultdict

res = defaultdict(list)
for key, val in sorted(dic.items()):
    res[val].append(key)

The same can be done with vanilla dictionary:

res = {}
for i, v in d_input.items():
    res[v] = [i] if v not in res.keys() else res[v]   [i]

A neat solution using pandas:

import pandas as pd

pd.Series(dic).reset_index().groupby(0).agg(list).to_dict()['index']

CodePudding user response:

def reverse_dict(d):
    inv = {}
    for k, v in d.items():
        if v in inv:
            inv[v].append(k)
        else:
            inv[v] = [k]
    return inv

dic = {
  "jane": "doe",
  "remy": "ma",
  "haaland": "buuk",
  "adam": "doe",
}

print(reverse_dict(dic))
  • Related