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
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')]}
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}
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