简体   繁体   中英

Convert a list and list of list to a dict in python

I have two lists ['a', 'b', 'c'] and [[1,2,3], [4,5,6]]

I am expecting an output {'a':[1,4], 'b':[2,5], 'c':[3,6]} without using a for loop.

Using zip :

>>> l1 = ['a', 'b', 'c']
>>> l2 = [[1,2,3], [4,5,6]]
>>> dict(zip(l1, zip(*l2)))  # zip(*l2) => [(1, 4), (2, 5), (3, 6)]
{'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}

UPDATE

If you want to get string-list mapping, using dict comprehension :

>>> {key:list(value) for key, value in zip(l1, zip(*l2))}
{'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

As it says in the other answer you should probably use zip. But if you want to avoid other third party libraries you can do it manually by calling a for loop on each element and adding to your dictionary manually.

Without a for Loop.

list1 = ['a', 'b', 'c']
list2 = [[1,2,3], [4,5,6]]
flat = reduce(lambda x,y: x+y,list2)
d = {}
df = dict(enumerate(flat))

def create_dict(n):
  position = flat.index(df[n])%len(list1)
  if list1[position] in d.keys():
     d[list1[position]].append(df[n])
  else:
     d[list1[position]] = [df[n]]

map( create_dict, df)
print d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM