Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of tuples to dictionary

Tags:

python

In Python 2.7, suppose I have a list with 2 member sets like this

d = [(1, 'value1'), (2, 'value2'), (3, 'value3')]

What is the easiest way in python to turn it into a dictionary like this:

d = {1 : 'value1', 2 : 'value2', 3 : 'value3'}

Or, the opposite, like this?

d = {'value1' : 1, 'value2': 2, 'value3' : 3}

Thanks

like image 361
Doo Dah Avatar asked Jan 20 '26 18:01

Doo Dah


2 Answers

The dict constructor can take a sequence. so...

dict([(1, 'value1'), (2, 'value2'), (3, 'value3')])

and the reverse is best done with a dictionary comprehension

{k: v for v,k in [(1, 'value1'), (2, 'value2'), (3, 'value3')]}
like image 198
John La Rooy Avatar answered Jan 23 '26 07:01

John La Rooy


If your list is in the form of a list of tuples then you can simply use dict().

In [5]: dict([(1, 'value1'), (2, 'value2'), (3, 'value3')])
Out[5]: {1: 'value1', 2: 'value2', 3: 'value3'}

A dictionary comprehension can be used to construct the reversed dictionary:

In [13]: { v : k for (k,v) in [(1, 'value1'), (2, 'value2'), (3, 'value3')] }
Out[13]: {'value1': 1, 'value2': 2, 'value3': 3}
like image 30
cmh Avatar answered Jan 23 '26 07:01

cmh