[英]How to iterate through dictionary with lists as values
Suppose I have the following dictionary:假设我有以下字典:
x = {'a': [1,2,3], 'b': [4,5,6], 'c':[5,6,7]}
I need to convert this into three dictionaries that look like:我需要将其转换为三个字典,如下所示:
{'a':1,'b':4,'c':5}
{'a':2,'b':5,'c':6}
{'a':3,'b':7,'c':7}
Essentially three dictionaries that have the same keys and values that correspond to the same index in each value.本质上是三个字典,它们具有相同的键和值,对应于每个值中的相同索引。
I can do this iteratively but I was wondering if there was a move concise and efficient way of doing this without having a nested for loop.我可以迭代地执行此操作,但我想知道是否有一种简洁有效的方法可以在没有嵌套 for 循环的情况下执行此操作。
假设您知道一个键(例如a
)并且您知道列表的长度都相同..
[ dict((k,v[i]) for k,v in x.items()) for i in range(len(x['a'])) ]
You can create a list of values for each dictionary, then iterate to get a list of dictionaries:您可以为每个字典创建一个值列表,然后迭代以获取字典列表:
x = {'a': [1,2,3], 'b': [4,5,6], 'c':[5,6,7]}
myValues = list(zip(*x.values()))
myList = [dict(zip(x.keys(), item)) for item in myValues]
print(myList)
[{'a': 1, 'b': 4, 'c': 5}, {'a': 2, 'b': 5, 'c': 6}, {'a': 3, 'b': 6, 'c': 7}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.