Reputation: 4029
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
Upvotes: 2
Views: 364
Reputation: 133514
>>> d = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
>>> dict(d)
{1: 'value1', 2: 'value2', 3: 'value3'}
>>> dict(map(reversed, d))
{'value3': 3, 'value2': 2, 'value1': 1}
Upvotes: 0
Reputation: 10927
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}
Upvotes: 4
Reputation: 250891
>>> lis = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
Use dict()
for the first one:
>>> dict(lis)
{1: 'value1', 2: 'value2', 3: 'value3'}
And a dict comprehension for the second one:
>>> {v:k for k,v in lis}
{'value3': 3, 'value2': 2, 'value1': 1}
dict()
converts an iterable into a dict:
>>> print dict.__doc__
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Upvotes: 3
Reputation: 56467
lst = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
To turn it to dict, just do
dict(lst)
to reverse it, you can do
dict((b,a) for a,b in lst)
Upvotes: 2
Reputation: 71939
dict(my_list)
should probably do the trick. Also, I think you have a list of tuples, not sets.
Upvotes: 1
Reputation: 304137
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')]}
Upvotes: 7