[英]How to iterate through a list of dictionaries
我的代碼是
index = 0
for key in dataList[index]:
print(dataList[index][key])
似乎可以很好地打印index = 0
的字典鍵的值。 但是,我不知道如何遍歷dataList
中未知數量的字典。
您可以迭代list
的len
range
的索引:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
或者您可以使用帶有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
你甚至可以直接遍歷列表中的元素:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
只需遍歷字典的值,甚至可以不進行任何查找:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
或者將迭代包裝在列表理解或生成器中,稍后解包:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
可能性是無止境。 這是一個選擇你喜歡什么的問題。
您可以輕松地做到這一點:
for dict_item in dataList:
for key in dict_item:
print dict_item[key]
它將遍歷列表,並且對於列表中的每個字典,它將遍歷鍵並打印其值。
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}')
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.
"""提供最大靈活性並且對我來說似乎更動態的方法如下:"""
def extract_fullnames_as_string(list_of_dictionaries):
result = ([val for dic in list_of_dictionaries for val in
dic.values()])
return ('My Dictionary List is ='result)
dataList = [{'first': 3, 'last': 4}, {'first': 5, 'last': 7},{'first':
15, 'last': 9},{'first': 51, 'last': 71},{'first': 53, 'last': 79}]
print(extract_fullnames_as_string(dataList))
"""這樣一來,Datalist 可以是任何格式的 Dictionary 格式,我發現,否則你最終會處理格式問題。試試下面的方法,它仍然可以工作......"" "
dataList1 = [{'a': 1}, {'b': 3}, {'c': 5}]
dataList2 = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first':
'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(dataList1))
print(extract_fullnames_as_string(dataList2))
另一個 pythonic 解決方案是使用集合模塊。
這是一個示例,我想生成一個僅包含 'Name' 和 'Last Name' 值的字典:
from collections import defaultdict
test_dict = [{'Name': 'Maria', 'Last Name': 'Bezerra', 'Age': 31},
{'Name': 'Ana', 'Last Name': 'Mota', 'Age': 31},
{'Name': 'Gabi', 'Last Name': 'Santana', 'Age': 31}]
collect = defaultdict(dict)
# at this moment, 'key' becomes every dict of your list of dict
for key in test_dict:
collect[key['Name']] = key['Last Name']
print(dict(collect))
輸出應該是:
{'Name': 'Maria', 'Last Name': 'Bezerra'}, {'Name': 'Ana', 'Last Name': 'Mota'}, {'Name': 'Gabi', 'Last Name': 'Santana'}
有多種方法可以遍歷字典列表。 但是,如果您喜歡Pythonic代碼,請考慮以下方法,但首先,讓我們使用data_list
而不是dataList
因為在 Python 中, snake_case優於camelCase 。
# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key in element:
print(key, element[key])
Output
Alice 10
Bob 7
Charlie 5
解釋:
for element in data_list:
-> element
將在每次迭代時成為data_list
中的字典,即第一次迭代中為{'Alice': 10}
,第二次迭代中為{'Bob': 7}
,以及{'Charlie': 5}
,在第三次迭代中。for key in element:
-> key
將是每次迭代時element
的鍵,因此當element
為{'Alice': 10}
時, key
的值將是'Alice'
。 請記住, element
可以包含更多鍵,但在這個特定示例中它只有一個。print(key, element[key])
-> 它打印key
key
key
和element
的值,即它訪問 `element.# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key, value in element.items():
print(key, value)
此代碼段的 output 與上一個相同。
解釋:
for element in data_list:
-> 它與之前代碼中的解釋相同。for key, value in element.items():
-> 在每次迭代中, element.items()
將返回一個包含兩個元素的元組。 前者元素是鍵,后者是與該鍵關聯的值,因此當element
為{'Alice': 10}
時, key
的值為'Alice'
,值的value
10
。 請記住,該字典只有一個鍵值對。print(key, value)
-> 它打印key
和value
。如前所述,有多種方法可以遍歷字典列表,但要使您的代碼更加 Pythonic,請避免使用索引或 while 循環。
有一個類似的問題,通過使用單個 for 循環遍歷列表來修復我的問題,請參閱代碼片段
de = {"file_name":"jon","creation_date":"12/05/2022","location":"phc","device":"s3","day":"1","time":"44692.5708703703","year":"1900","amount":"3000","entity":"male"}
se = {"file_name":"bone","creation_date":"13/05/2022","location":"gar","device":"iphone","day":"2","time":"44693.5708703703","year":"2022","amount":"3000","entity":"female"}
re = {"file_name":"cel","creation_date":"12/05/2022","location":"ben car","device":"galaxy","day":"1","time":"44695.5708703703","year":"2022","amount":"3000","entity":"male"}
te = {"file_name":"teiei","creation_date":"13/05/2022","location":"alcon","device":"BB","day":"2","time":"44697.5708703703","year":"2022","amount":"3000","entity":"female"}
ye = {"file_name":"js","creation_date":"12/05/2022","location":"woji","device":"Nokia","day":"1","time":"44699.5708703703","year":"2022","amount":"3000","entity":"male"}
ue = {"file_name":"jsdjd","creation_date":"13/05/2022","location":"town","device":"M4","day":"5","time":"44700.5708703703","year":"2022","amount":"3000","entity":"female"}
d_list = [de,se,re,te,ye,ue]
for dic in d_list:
print (dic['file_name'],dic['creation_date'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.