如果您需要遍歷多個嵌套字典,如下面的兩個,您將如何僅從帶有鍵“fruit”的子字典中獲取鍵和值?目標是創建一個包含三列的資料框:“顏色”、“價格”和“水果”。
{'A':{'color':'red','price':22, 'fruit':'apple'},'B':{'color':'orange','price':123, 'vegetable':'carrot'}}
{'X':{'color':'yellow','price':2, 'fruit':'banana'},'Y':{'color':'yellow','price':14, 'vegetable':'melon'}}
uj5u.com熱心網友回復:
使用帶有if條件的字典理解。
stock = {'A':{'color':'red','price':22, 'fruit':'apple'},'B':{'color':'orange','price':123, 'vegetable':'carrot'}}
only_fruit = {key: value for key, value in stock.items() if 'fruit' in value}
uj5u.com熱心網友回復:
看起來多個嵌套字典是不同的變數。
你可以試試這個:
import pandas as pd
nested_dict1 = {'A':{'color':'red','price':22, 'fruit':'apple'},'B':{'color':'orange','price':123, 'vegetable':'carrot'}}
nested_dict2 = {'X':{'color':'yellow','price':2, 'fruit':'banana'},'Y':{'color':'yellow','price':14, 'vegetable':'melon'}}
final_dict = {"fruit" :[], "color":[], "price":[]}
for key, val in nested_dict1.items():
if "fruit" in val:
final_dict["fruit"].append(val["fruit"])
final_dict["color"].append(val["color"])
final_dict["price"].append(val["price"])
for key, val in nested_dict2.items():
if "fruit" in val:
final_dict["fruit"].append(val["fruit"])
final_dict["color"].append(val["color"])
final_dict["price"].append(val["price"])
df = pd.DataFrame(final_dict)
print(df)
輸出:
fruit color price
0 apple red 22
1 banana yellow 2
在這里,我為 2 個不同的多個嵌套字典創建了 2 個不同的回圈。根據您的用例,您可以對其進行優化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329509.html
下一篇:Terraform匯入地圖資源
