WojonsTech
WojonsTech

Reputation: 1277

Python Ordered Dictionary to regular Dictionary

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

Upvotes: 3

Views: 1322

Answers (3)

Stephane Rolland
Stephane Rolland

Reputation: 39926

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

Upvotes: 1

NPE
NPE

Reputation: 500913

Just apply dict() to the list:

In [2]: dict([('first', 1), ('second', 2), ('third', 3)])
Out[2]: {'first': 1, 'second': 2, 'third': 3}

Upvotes: 4

Volatility
Volatility

Reputation: 32308

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}

Upvotes: 9

Related Questions