[英]convert a dictionary into a dictionary with list of values in python using two list
I have two list like我有两个列表
['a','b','c']
['x','y','z']
I want to create a dictionary which holds values as list like,我想创建一个字典,将值保存为列表,例如,
{'a':['x'],'b':['y'],'c':['z']}
I am using like this but gives me values not in list :我是这样使用的,但给了我不在列表中的值:
dictionary = dict(zip(out_head, (select11)))
Please suggest.请建议。
This creates a list for each element in select11
这
select11
每个元素创建一个列表
dictionary = dict(zip(out_head,
([x] for x in select11)
))
Alternatively (@kpie reminds me of dict-comprehension notation):或者(@kpie 让我想起 dict-comprehension 符号):
dictionary = {k:[v] for k,v in zip(out_head, select11)}
Try calling list
on each element in the second list before zipping them.在压缩它们之前,尝试在第二个列表中的每个元素上调用
list
。
x, y = ['a','b','c'], ['x','y','z']
new = dict(zip(x, [list(i) for i in y]))
print new
I think the syntax you are looking for is this.我认为您正在寻找的语法是这样的。
a = [1,2,3]
b = ['a','b','c']
d = {k:[v] for (k,v) in [(q,w) for q in a for w in b]}
a = ['a','b','c'] b = ['x','y','z']
a = ['a','b','c'] b = ['x','y','z']
dict(zip(a,map(list, b)))
dict(zip(a,map(list, b)))
The map(list) wraps each member of list b in its own list, which is what you say you want. map(list) 将列表 b 的每个成员包装在自己的列表中,这就是您所说的。
Use this.用这个。
keys = ['a', 'b', 'c']
values = ['x', 'y', 'z']
dictionary = dict(zip(keys, list(values)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.