简体   繁体   中英

Return a dictionary with keys for a given dictionary's values and vice versa

How would I, in a function, create a dictionary who's keys are a given dictionary's values, and vice versa, where the given dictionary has multiple values per key? For example, given a dictionary:

d = {"1":["a","b"],"2":["b","a","c"],"3":["c","d"]}

I'd need to return a dictionary like:

d2 = {"a":["1","2"],"b":["1","2"],"c":["2","3"],"d":["3"]}

My only idea was to make a list of all values, then manually check each key for each value, but I couldn't figure out how to do that without knowing the number of keys and values. Any help would be vastly appreciated.

Try:

{letter: [key for key in d if letter in d[key]] for letter in set(letter for key in d for letter in d[key])}

Explanation: set(letter for key in d for letter in d[key]) is a set of all letters that appears in the original dict. Then we make a new dict, in which every entry is letter: [key for key in d if letter in d[key]] , which means one of the letters, mapping to a list of numbers that mapped to it in the original dict.

Easy using collections.defaultdict() which defaults as list

  • loop on the sorted key/value couple
  • inner loop on the value items
  • for each value item, create/update list with original dict key

code:

import collections

d3 = collections.defaultdict(list)

for k,v in sorted(d.items()):
    for vi in v:
        d3[vi].append(k)  # create list or append to existing list

print(dict(d3))

result:

{'b': ['1', '2'], 'd': ['3'], 'c': ['2', '3'], 'a': ['1', '2']}
data = [(key, value) for key, values in d.items() for value in values]
d2 = defaultdict(list)

for value, key in data:
    d2[key].append(value)
    print(key, value)

Here is a solution I found 5 years ago

from operator import itemgetter
from itertools import groupby
d = {'1': ['a', 'c'],'2': ['a', 'b', 'c'], '3': ['b']}
d2 = {x: [t[1] for t in group] for (x, group) in  groupby(sorted(((j, k) for k, v in d.items() for j in v), key=itemgetter(0)), key=itemgetter(0))}
# {'a': ['1', '2'], 'c': ['1', '2'], 'b': ['2', '3']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM