imasnake
imasnake

Reputation: 355

Assign single value to a single key from dictionary key with multiple values

I have seen many forums on assigning multiple values to a key in python, but none going the other way. What I want is to assign a single key to a single value, and then flip it.

What I have:

myDict = {1: ['id1', 'id2', 'id3'], 2: ['id4', 'id5'], 3: ['id6']}

What I am looking to do:

myDict = {'id1': 1, 'id2': 1, 'id3': 1, 'id4': 2, 'id5': 2, 'id6': 3}

I have been searching the forums and cant figure out how to assign a single value to a single key, but I'm guessing the 'flip' part would look something like this:

myDict = {y:x for x,y in MyDict.iteritems()}

Any help would be very appreciated.

EDIT: All id's will be unique (not chance of duplicates/multiples)

Upvotes: 1

Views: 229

Answers (4)

imasnake
imasnake

Reputation: 355

SOLUTION:

{id:x for x,y in myDict.iteritems() for id in y}

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

You can achieve this via:

dict((x,k) for k, v in myDict.iteritems() for x in v)

OR:

{x: k for k, v in myDict.iteritems() for x in v}

OR (not a pythonic approach):

reverse_dict = {}
for k in a:
    for x in myDict[k]:
        reverse_dict[x] = k

Upvotes: 1

alepeino
alepeino

Reputation: 9771

You need to nest 2 comprehensions, since you have a list of values for each of the key-value pairs in your original dict.

How about

{id:x for x,y in myDict.iteritems() for id in y}

Upvotes: 3

timgeb
timgeb

Reputation: 78790

Since you cannot have duplicate ids across the lists, a relatively simple comprehension can do it:

>>> myDict = {1: ['id1', 'id2', 'id3'], 2: ['id4', 'id5'], 3: ['id6']}
>>> {id:k for k,lst in myDict.iteritems() for id in lst}
{'id6': 3, 'id4': 2, 'id5': 2, 'id2': 1, 'id3': 1, 'id1': 1}

Upvotes: 1

Related Questions