dease
dease

Reputation: 3076

Python map list of two-element tuples into key:value dict

I have a rest API endpoint which returns list of available countries in JSON format, like:

[["ALL","Albania Lek"],["AFN","Afghanistan Afghani"],["ARS","Argentina Peso"],["AWG","Aruba Guilder"],["AUD","Australia Dollar"]]

I need to convert it to

{
"ALL":"Albania Lek",
"AFN":"Afghanistan Afghani",
"ARS":"Argentina Peso"
}

How can I do this quickly and efficiently?

Upvotes: 0

Views: 71

Answers (3)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15588

I think

{k:v for k,v in the_list}

Is better than dict(the_list) because it does not invoke a function. So performance-wise comprehension wins.

See Tests: https://doughellmann.com/blog/2012/11/12/the-performance-impact-of-using-dict-instead-of-in-cpython-2-7-2/

And: https://medium.com/@jodylecompte/dict-vs-in-python-whats-the-big-deal-anyway-73e251df8398

Upvotes: 0

Óscar López
Óscar López

Reputation: 236140

The dict() constructor builds dictionaries directly from sequences of key-value pairs, as stated in the documentation. So it's as simple as this:

the_list = [['ALL', 'Albania Lek'],
            ['AFN', 'Afghanistan Afghani'], 
            ['ARS', 'Argentina Peso'], 
            ['AWG', 'Aruba Guilder'],
            ['AUD', 'Australia Dollar']]

dict(the_list)

=> {
     'AWG': 'Aruba Guilder',
     'ALL': 'Albania Lek', 
     'ARS': 'Argentina Peso',
     'AFN': 'Afghanistan Afghani',
     'AUD': 'Australia Dollar'
   }

Upvotes: 4

dfundako
dfundako

Reputation: 8324

Another 1 liner option is dict comprehension

{x[0]:x[1] for x in the_list}

Upvotes: -1

Related Questions