2

I have a list like this:

[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]

I want to convert this list into dictionary like this:

{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}

How to do something like this?

jamylak
  • 128,818
  • 30
  • 231
  • 230
pynovice
  • 7,424
  • 25
  • 69
  • 109

3 Answers3

5

Try this:

dict(zip(xs[0], zip(*xs[1:])))

For lists as values of the dict:

dict(zip(xs[0], map(list, zip(*xs[1:]))))
jamylak
  • 128,818
  • 30
  • 231
  • 230
simonzack
  • 19,729
  • 13
  • 73
  • 118
0
>>> lis  = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
>>> keys, values = lis[0],lis[1:]
>>> {key:[val[i] for val in values] 
                                  for i,key in enumerate(keys) for val in values}
{'ok.txt': [10, 'first_one', 'done'], 'hello': [20, 'second_one', 'pending']}
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

You can make use of the built-in zip function to perform this easily like this:

list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
dict_from_list = dict(zip(list_of_list[0], zip(*list_of_list[1:])))

In this, the interior zip(*list_of_list[1:]) will convert the list of lists from list_of_list(except the first element) to a list of tuples. The tuple is order preserved and is again zipped with the supposed keys to form a list of tuples, which is converted to a proper dictionary through the dict function.

Please note that this will have tuple as data type for the values in the dictionary. As per your example, the one-liner will give:

{'ok.txt': (10, 'first_one', 'done'), 'hello': (20, 'second_one', 'pending')}

In order to have a list, you have to map the interior zip with the list function. (i.e) change

zip(*list_of_list[1:]) ==> map(list, zip(*list_of_list[1:]))

For info about zip function, click here

Edit: I just noticed that the answer is same as that of the one given by Simon. Simon gave it lot quicker when I was trying the code in terminal and I didn't noticed his answer when I was posting.

thiruvenkadam
  • 4,170
  • 4
  • 27
  • 26