[英]extract item from dictionary in dictionary with for loop
我想用 for 循環將字典中的字典元素附加到列表中,但 i["fruit"] 似乎是一個索引。 我該如何解決?
dict_1 = {"number_1": {"fruit": ['banana'],
"no": ['1']
},
"number_2": {"fruit": ['apple'],
"no": ['2']
}
}
list_1 = [i["fruit"] for i in dict_1["number_1"]]
print list_1
# print dict_1["number_1"]["fruit"]
你的錯誤是你迭代dict_1['number_1'
- 它只返回該字典的鍵:
for item in dict_1['number_1']:
print item
fruit
no
如果您還想迭代這些值,則需要添加.items()
:
for item, value in dict_1['number_1'].items():
print item
fruit ['banana']
no ['1']
因此,如果您只想要香蕉,請使用dict_1['number_1'].items()
迭代您的字典並將value
部分附加到列表中:
list1 = []
for item, value in dict_1['number_1'].items():
list1.append(value)
你不能只直接得到 'number_1' 的 ['banana'] 因為字典在 python 中是無序的,而且我們不知道出現的是哪個鍵值對,這就是為什么我們不知道 'number_1' 什么時候會出現出現並且當 'number_2' 作為第一個鍵值對時。
無序字典有兩種可能的解決方案:
第一個解決方案獲取所有水果名稱:
dict_1 = {"number_1": {"fruit": ['banana'],
"no": ['1']
},
"number_2": {"fruit": ['apple'],
"no": ['2']
}
}
for key,value in dict_1.items():
print(value['fruit'])
第二個是
如果你特別想要香蕉,那么首先檢查密鑰,因為正如我所說的字典是無序的。
for key,value in dict_1.items():
if key=='number_1':
print(value['fruit'])
其他解決方案是,如果您不想檢查密鑰,則使用集合模塊中的有序字典:
from collections import OrderedDict
my_dict=OrderedDict()
my_dict['number_1'] = OrderedDict()
my_dict['number_1']['fruit']=['banana']
my_dict['number_1']['no']=['1']
my_dict['number_2']=OrderedDict()
my_dict['number_2']['fruit']=['apple']
my_dict['number_2']['no']=['2']
print(list(list(my_dict.values())[0].values())[0])
輸出:
['banana']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.