I have something like
[('first', 1), ('second', 2), ('third', 3)]
and i want a built in function to make something like
{'first': 1, 'second': 2, 'third': 3}
Is anyone aware of a built-in python function that provides that instead of having a loop to handle it?
Needs to work with python >= 2.6
dict
can take a list of tuples and convert them to key-value pairs.
>>> lst = [('first', 1), ('second', 2), ('third', 3)]
>>> dict(lst)
{'second': 2, 'third': 3, 'first': 1}
Just apply dict()
to the list:
In [2]: dict([('first', 1), ('second', 2), ('third', 3)])
Out[2]: {'first': 1, 'second': 2, 'third': 3}
Not as much elegant/simple as dict(my_list)
proposed by Volatility's answer...
I would also suggest:
my_list = [('first', 1), ('second', 2), ('third', 3)]
my_dict = {k:v for k,v in my_list}
It's more useful when you have to filter some elements from the original sequence.
my_list = [('first', 1), ('second', 2), ('third', 3)]
my_dict = {k:v for k,v in my_list if k!='third'}
or
my_dict = {k:v for k,v in my_list if test_value(v)} # test_value being a function return bool
as comments says it only works for python >= 2.7
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.