Python 3.5遍历字典列表

C. *_*ner 17 python dictionary for-loop list python-3.5

我的代码是

index = 0
for key in dataList[index]:
    print(dataList[index][key])
Run Code Online (Sandbox Code Playgroud)

似乎可以正常工作打印index = 0的字典键的值.

但是对于我的生活,我无法弄清楚如何将这个for循环放在for循环中,循环遍历未知数量的字典 dataList

MSe*_*ert 22

你可以只遍历的索引rangelen你的list:

dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
    for key in dataList[index]:
        print(dataList[index][key])
Run Code Online (Sandbox Code Playgroud)

或者你可以使用带有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
Run Code Online (Sandbox Code Playgroud)

你甚至可以直接迭代列表中的元素:

dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
    for key in dic:
        print(dic[key])
Run Code Online (Sandbox Code Playgroud)

通过迭代字典的值,它甚至可以没有任何查找:

dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
    for val in dic.values():
        print(val)
Run Code Online (Sandbox Code Playgroud)

或者将迭代包装在list-comprehension或generator中,然后将它们解压缩:

dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
Run Code Online (Sandbox Code Playgroud)

可能性是无止境.这是您喜欢的选择问题.


小智 12

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}')
Run Code Online (Sandbox Code Playgroud)


Avi*_*mka 7

你可以很容易地做到这一点:

for dict_item in dataList:
  for key in dict_item:
    print dict_item[key]
Run Code Online (Sandbox Code Playgroud)

它将遍历列表,并且对于列表中的每个字典,它将遍历键并打印其值。