Home > other >  Convert the given lists into dictionary using Python?
Convert the given lists into dictionary using Python?

Time:01-19

Lets say we have a set of input lists:

lst= [country,usa,uk,india,japan],
[city,tokyo,berlin,moscow,abudhabi],
[planet,earth,mars,venus]

We want to create a dictionary in python for each of these lists, so that the output looks like:

mydict= {country:[usa,uk,india,japan]},
{city:[tokyo,berlin,moscow,abudhabi]},
{planet:[earth,mars,venus]}

CodePudding user response:

You can use dictionary comprehension and slicing for that

lst= [[country,usa,uk,india,japan],
[city,tokyo,berlin,moscow,abudhabi],
[planet,earth,mars,venus]]

result = [{l[0]:l[1:]} for l in lst]

here I have assumed that lst is a list of lists you want to create a list of dictionaries from it. This was not 100% clear from you question.

CodePudding user response:

I am assuming that you did not use strings and the list you gave was not a nested list so I modified the code based on my understanding of your code.

The list is defined by

lst= [['country','usa','uk','india','japan'],
['city','tokyo','berlin','moscow','abudhabi'],
['planet','earth','mars','venus']]

to convert it to a dictionary I used

dict={lst[0][0]:lst[0][1:5],
      lst[1][0]:lst[1][1:5],
      lst[2][0]:lst[2][1:4]}

and this is what printing the dictionary looks like

{'city': ['tokyo', 'berlin', 'moscow', 'abudhabi'],
 'country': ['usa', 'uk', 'india', 'japan'],
 'planet': ['earth', 'mars', 'venus']}

CodePudding user response:

Assuming this valid python input:

lst = [['country','usa','uk','india','japan'],
       ['city','tokyo','berlin','moscow','abudhabi'],
       ['planet','earth','mars','venus']]

Use zip, and the dict constructor:

keys, *vals = zip(*lst)
d = dict(zip(keys, map(list,vals)))

Output:

{'country': ['usa', 'uk', 'india', 'japan'],
 'city': ['tokyo', 'berlin', 'moscow', 'abudhabi'],
 'planet': ['earth', 'mars', 'venus']}

CodePudding user response:

Assuming this is the input you want:

lst = [['country','usa','uk','india','japan'],
       ['city','tokyo','berlin','moscow','abudhabi'],
       ['planet','earth','mars','venus']]

and the output is a single dictionary like this:

{'country': ['usa', 'uk', 'india', 'japan'], 'city': ['tokyo', 'berlin', 'moscow', 'abudhabi'], 'planet': ['earth', 'mars', 'venus']}

You can use dict comprehension with list unpacking to get the result:

mydict = {k: vals for (k, *vals) in lst}
  •  Tags:  
  • Related