0

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?

dease
  • 2,975
  • 13
  • 39
  • 75
  • Possible duplicates: [Create a dictionary with list comprehension in Python](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python/1747827#1747827) and [python tuple to dict](https://stackoverflow.com/questions/3783530/python-tuple-to-dict) – Patrick Haugh Dec 07 '18 at 14:57

3 Answers3

4

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'
   }
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

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

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
  • 1
    I just ran some timings (using 3.6.6), and this does not seem to be accurate. For a 10 million item list (`list(zip(range(10000000), range(10000000)))`), the comprehension had a time of `1.23 sec per loop` and the `dict` call had a time of `1.06 sec per loop` – Patrick Haugh Dec 07 '18 at 15:14
-1

Another 1 liner option is dict comprehension

{x[0]:x[1] for x in the_list}
dfundako
  • 8,022
  • 3
  • 18
  • 34