如何將專案(或行)動態添加到字典中?
這是我正在嘗試做的事情:
# Declare an empty dictionary that needs to be built
my_dictionary = {}
# A random list
my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]
# Routine/Function to add KEY and VALUES to this dictionary
for index in range(len(my_list)):
new_values = {"code": index, "item_name": my_list[index]}
my_dictionary.update(new_values)
print(my_dictionary)
問題是輸出不是我所期望的。print(my_dictionary) 給了我:
{'code': 4, 'item_name': 'item5'}
我期待所有的字典值都被插入到這里。相反,它只給了我最后一次迭代。因此 update() 方法不會將新值插入字典中。它只會更新現有記錄。那么如何插入新值?
更新:
我認為我需要的是一種創建嵌套字典的方法所以我期待:
my_dictionary =
{
"code": ...,
"Value": ...,
},
{
"code:" ...,
"value": ...
}
etc..
uj5u.com熱心網友回復:
my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]
for index in range(len(my_list)):
my_dictionary[index] = my_list[index]
print(my_dictionary)
->{0: 'item 1', 1: 'item 2', 2: 'item 3', 3: 'item 4', 4: 'item5'}
如果這不是您想要的,您需要用您想要的問題更新您的問題。
uj5u.com熱心網友回復:
另一種方法是使用字典推導
{index:val for index, val in enumerate(my_list)}
uj5u.com熱心網友回復:
不確定輸出應該是什么,因為從問題中不清楚。但是,如果您想要一個字典,其中鍵是串列中的索引位置,那么:
my_list = ["item 1", "item 2", "item 3", "item 4", "item5"]
dict_ = dict(enumerate(my_list))
print(dict_)
輸出:
{0: 'item 1', 1: 'item 2', 2: 'item 3', 3: 'item 4', 4: 'item5'}
在對問題進行編輯之后,似乎需要這樣做:
my_output = [{'code': i, 'item_name': n} for i, n in enumerate(my_list)]
print(my_output)
這使:
[{'code': 0, 'item_name': 'item 1'}, {'code': 1, 'item_name': 'item 2'}, {'code': 2, 'item_name': 'item 3'}, {'code': 3, 'item_name': 'item 4'}, {'code': 4, 'item_name': 'item5'}]
uj5u.com熱心網友回復:
那是因為字典的鍵是唯一的,因此同一個鍵不能有不同的值。因此,在 for 回圈的每次迭代中,您都會覆寫先前的值。您可以擁有具有相同鍵的字典串列。
print(["data":{"code": index, "item_name":val} for index, val in enumerate(my_list)])
[{'code': 0, 'item_name': 'item 1'},
{'code': 1, 'item_name': 'item 2'},
{'code': 2, 'item_name': 'item 3'},
{'code': 3, 'item_name': 'item 4'},
{'code': 4, 'item_name': 'item5'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504905.html