我的代码是
index = 0
for key in dataList[index]:
print(dataList[index][key])
似乎可以正常打印index = 0的字典键值。
但是对于我的生活,我无法弄清楚如何将这个for循环放在for循环中,该循环遍历dataList
答案 0 :(得分:11)
您可以迭代range
的{{1}} len
的索引:
list
或者您可以使用带有dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
计数器的while循环:
index
你甚至可以直接迭代列表中的元素:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
通过迭代字典的值,它甚至可以没有任何查找:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
或者将迭代包装在list-comprehension或generator中并稍后解压缩它们:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
可能性无穷无尽。这是你喜欢的选择问题。
答案 1 :(得分:4)
您可以轻松地执行此操作:
for dict_item in dataList:
for key in dict_item:
print dict_item[key]
它将迭代列表,对于列表中的每个字典,它将遍历键并打印其值。
答案 2 :(得分:0)
def extract_fullnames_as_string(list_of_dictionaries):
return list(map(lambda e : "{} {}".format(e['first'],e['last']),list_of_dictionaries))
names = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first': 'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(names))
#Well...the shortest way (1 line only) in Python to extract data from the list of dictionaries is using lambda form and map together.
答案 3 :(得分:-1)
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}')