Ajay Chinni
Ajay Chinni

Reputation: 840

Inverse a python Dictionary where values are list

I have this dictionary with keys and where values are in a list.

d = {'A':['A1','A2','A3'],'B':['B1','B2']}

I want output like this

inv_d = {'A1':'A','A2':'A','A3':'A','B1':'B','B2':'B'}

I am doing this

inv_d  = {v1 for v1 in v:k for k, v in d.items()} 

Getting error

  File "<ipython-input-14-96f1a52e0304>", line 2
    inv_d  = {v1 for v1 in v:k for k, v in d.items()}
                            ^
SyntaxError: invalid syntax

Upvotes: 1

Views: 84

Answers (5)

pratishtha
pratishtha

Reputation: 51

inv_d = {}
for k, v in d.items():
  for v1 in v:
    inv_d[k] = v1

Upvotes: 2

Sandeep
Sandeep

Reputation: 21144

You can iterate over dictionary without using items method and it iterates over the key. You could simply write it as follows:

inv_d = {value: key for key in d for value in d[key]}

Upvotes: 1

Bob
Bob

Reputation: 1070

You have to rewrite your code to the following:

>>> inv_d  = {v1:k for k, v in d.items() for v1 in v}
>>> inv_d
{'A1': 'A', 'A2': 'A', 'A3': 'A', 'B1': 'B', 'B2': 'B'

A short explanation. Let's say you just wanted to do this with normal for loops, you would write the following.

inv_d = {}
for k, v in d.items():
  for v1 in v:
    inv_d[k] = v1

To convert this to a single dict comprehension, you have to keep the same ordering of for loops:

{... for k, v in d.items()  for v1 in v}

Upvotes: 2

bigbounty
bigbounty

Reputation: 17368

{i:k for k,v in d.items() for i in v}

Output:

{'A1': 'A', 'A2': 'A', 'A3': 'A', 'B1': 'B', 'B2': 'B'}

Upvotes: 2

CDJB
CDJB

Reputation: 14516

With a slight edit to your solution, we get:

>>> {v1:k for k, v in d.items() for v1 in v}
{'A1': 'A', 'A2': 'A', 'A3': 'A', 'B1': 'B', 'B2': 'B'}

Upvotes: 2

Related Questions