简体   繁体   中英

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?

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

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

另一个1班轮选项是dict理解

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM