George Burrows
George Burrows

Reputation: 3501

Dictionary changing many values to many keys

I was just wondering if in the wonderful world of Python there is any way to go from something like this:

dict1 = {'a': [1,2,3], 'b': [4,5,6]}

to

dict2 = {'a':1, 'a':2, 'a':3,'b':4, 'b': 5, 'b': 6]

or equivalent, the order is irrelevant but I need some way of decomposing dict1 into something in which I can assign the numerical values to indices of a new list and the keys as the actual values of those indices e.g. dict1 would turn into:

[0, a, a, a, b, b, b] 

Any help would be appreciated, although the more idiot proof the answers the better.

I am indebted to you once again.

Upvotes: 1

Views: 130

Answers (2)

jfs
jfs

Reputation: 414675

If values represent indices then:

import itertools

dict1 = {'a': [1,2,3], 'b': [4,5,6]}

L = [None]*(max(itertools.chain(*dict1.values())) + 1)
for word, indexes in dict1.items():                          
    for i in indexes:                                     
        L[i] = word
print(L)
# -> [None, 'a', 'a', 'a', 'b', 'b', 'b']

Upvotes: 2

wim
wim

Reputation: 363183

Your dict2 makes no sense because dictionary keys must be unique.

I am pretty sure you can get what you want by iterating over dict1.items(), but I need some more clarification on what the expected output list looks like... in your example a and b are undefined and I don't know what the 0 at the start is representing.

Perhaps you wanted something like this?

dict2 = {}
for k,v in dict1.items():
  for x in v:
    dict2[x] = k

This would give you a dict2 like {1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'b'}. Be warned that duplicate entries in the unpacked values of dict1 could be overwritten by this loop.


Just for shits and giggles, the same thing in 1 line as an incomprehensible dict comprehension:

{x: k for (k,v) in dict1.items() for x in v}

Upvotes: 5

Related Questions