Python 3.5 遍历字典列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35864007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3.5 iterate through a list of dictionaries
提问by C. P. Wagner
My code is
我的代码是
index = 0
for key in dataList[index]:
print(dataList[index][key])
Seems to work fine for printing the values of dictionary keys for index = 0.
似乎可以很好地打印索引 = 0 的字典键的值。
But for the life of me I can't figure out how to put this for loop inside a for loop that iterates through the unknown number of dictionaries in dataList
但是对于我的生活,我无法弄清楚如何将这个 for 循环放在一个循环中,该循环遍历未知数量的字典 dataList
回答by MSeifert
You could just iterate over the indices of the range
of the len
of your list
:
你可以只遍历的索引range
的len
你的list
:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
or you could use a while loop with an index
counter:
或者您可以使用带有index
计数器的 while 循环:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
you could even just iterate over the elements in the list directly:
你甚至可以直接遍历列表中的元素:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
It could be even without any lookups by just iterating over the values of the dictionaries:
它甚至可以通过迭代字典的值而无需任何查找:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
Or wrap the iterations inside a list-comprehension or a generator and unpack them later:
或者将迭代包装在列表理解或生成器中,然后再解压它们:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
the possibilities are endless. It's a matter of choice what you prefer.
可能性是无止境。这是一个选择你喜欢什么的问题。
回答by Avihoo Mamka
You can easily do this:
你可以很容易地做到这一点:
for dict_item in dataList:
for key in dict_item:
print dict_item[key]
It will iterate over the list, and for each dictionary in the list, it will iterate over the keys and print its values.
它将遍历列表,并且对于列表中的每个字典,它将遍历键并打印其值。
回答by atufa shireen
use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
for dic in use:
for val,cal in dic.items():
print(f'{val} is {cal}')