Reputation: 3076
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
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.
And: https://medium.com/@jodylecompte/dict-vs-in-python-whats-the-big-deal-anyway-73e251df8398
Upvotes: 0
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
Reputation: 8324
Another 1 liner option is dict comprehension
{x[0]:x[1] for x in the_list}
Upvotes: -1