Home > database >  Convert a List of Lists into a dictionary? in python
Convert a List of Lists into a dictionary? in python

Time:06-17

I Want to convert a list of lists into a dictionary where every sub-list are the key value in the dictionary for example

array = [[a,b],[c,d],[e,f]]

I want to be output like this

dict = { a:b,c:d,e:f }

CodePudding user response:

>>> array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> dict(array)
{'a': 'b', 'c': 'd', 'e': 'f'}

CodePudding user response:

Use a dictionary comprehension.
Arrays are called lists in Python, so rename your variable (lst is too generic, use a more specific name).
Remember to quote the strings.

lst = [['a','b'],['c','d'],['e','f']]
dct = {x[0]: x[1] for x in lst}
print(dct)
# {'a': 'b', 'c': 'd', 'e': 'f'}
  • Related