将词典分配给列表

时间:2018-01-26 11:15:52

标签: python list dictionary

刚接触Python,我正在研究以下代码:

a_0 = {"what": "b"}
a_1 = {"what": "c"}
a_2 = {"what": "d"}

items = [] # empty list

for i_no in range(10): # fill the list with 10 identical a_0 dicts
    i_new = dict(a_0)
    items.append(i_new)

for i in items[0:5]: # change the first 5 items
    if i["what"] == "b": # try to change the 'i' to be a_1 dicts
        i = dict(a_1)
        # print(i) shows changes

for i in items: 
    print(i)
    # print(i) does not show changes

如果上述更改有效,则前5个项应与a_1相同,而后5个不变。但印刷的结果与我的期望不符,这使我感到困惑。我想知道我是否遗漏了什么。有没有更方便的方法来更改列表中的每个字典?非常感谢。

2 个答案:

答案 0 :(得分:0)

for i in items[0:5]: # change the first 5 items
    if i["what"] == "b": # try to change the 'i' to be a_1 dicts
        i = dict(a_1)
        # print(i) shows changes

创建循环时... i是一个局部变量,其中包含位置[0:5]的字典

当你这样做时:

i = dict(a_1)

您正在更改局部变量,但不更改列表中的值。迭代索引并直接在列表中更改

for i in range(0, 5): # change the first 5 items
    if items[i]["what"] == "b": # try to change the 'i' to be a_1 dicts
        items[i] = dict(a_1)
        # print(items[i]) shows changes

现在您已更改列表中的项目,而不是本地变量的值

答案 1 :(得分:0)

那是因为你正试图改变“我”。它只保存'项目中每个项目的价值。名单。试试这个:

a_0 = {"what": "b"}
a_1 = {"what": "c"}
a_2 = {"what": "d"}

items = []

for i_no in range(10):
    i_new = dict(a_0)
    items.append(i_new)

for index,i in enumerate(items[0:5]):
    if i["what"] == "b": 
        items[index] = dict(a_1)

for i in items: 
    print i