I have a dictionary, the keys are integer values and the values are a list of strings. I want to make it vice versa, the string become key and integers become values. Like:
first design:
{1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
second design:
{"a": [1,2,3,6], "b":[2,4], "cd":[4,6]}
any clue? Thanks
A simple approach would be to create a defaultdict
that provides an empty list for new keys, and then for each list in your current dict, create a key for each element and append the original dict key to the new list:
from collections import defaultdict
orig = {1: ['a'], 2: ['a', 'b'], 3: ['a'], 4: ['b', 'cd'], 6: ['a', 'cd']}
d = defaultdict(list)
for k, v in orig.items():
for string in v:
d[string].append(k)
# d = {'a': [1, 2, 3, 6], 'b': [2, 4], 'cd': [4, 6]}
For the love of one-liners (note: heavily inefficient!):
d2 = {val: [key for key in d if val in d[key]] for lst in d.itervalues() for val in lst}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With