[英]Iterate over lists inside a dictionary
Is there any way to iterate over lists inside a dictionary.有什么方法可以遍历字典中的列表。 A key inside dictionary contains a list which needs to be iterated over separately from the other lists.
字典中的键包含一个列表,需要与其他列表分开迭代。 When I try to iterate over the dictionary, it iterates over the 0th element of each key.value instead of iterating over one list.
当我尝试遍历字典时,它遍历每个 key.value 的第 0 个元素,而不是遍历一个列表。
as an example, the dictionary below should be iterated.例如,应该迭代下面的字典。 First the iteration should be able to access the list inside 'a' separately and the list inside 'b'.
首先,迭代应该能够分别访问“a”内的列表和“b”内的列表。
d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}
To iterate in the lists inside the dictionary you can try something like this,要迭代字典中的列表,您可以尝试这样的操作,
d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}
for key in d:
for item in d[key]:
print(item) #Change this line to whatever you want to do
To iterate only on a
do,只迭代
a
do,
for item in d["a"]:
print(item)
d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}
for k,v in d.items():
for item in d[k]:
print(item)
You can use a list comprehension like so:您可以像这样使用列表理解:
[print(num) for lst in d.values() for num in lst]
The list is not saved at the end.最后不保存列表。
Using from_iterable
:使用
from_iterable
:
import itertools
d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}
for key, value in (
itertools.chain.from_iterable((itertools.product((k,), v) for k, v in d.items()))):
if(key=='a'):
print(value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.