Python uanble更改字典元素

Python uanble更改字典元素,python,dictionary,Python,Dictionary,嘿,我试图在for循环中使用if语句来更改dictionary中的元素,当我在第一个for循环中包括properties dictionary时,它似乎工作得很好。否则,我无法根据需要更改元素 我想做的是,创建一个空列表。然后添加30个具有相同属性的字典项。创建字典后,我试图使用if语句更改列表中前3个元素的属性。然后打印列表中的前6个元素以检查是否应用了更改 properties1={'color':'silver','weight':45,'Height':5.5,'planet':'mar

嘿,我试图在for循环中使用if语句来更改dictionary中的元素,当我在第一个for循环中包括properties dictionary时,它似乎工作得很好。否则,我无法根据需要更改元素

我想做的是,创建一个空列表。然后添加30个具有相同属性的字典项。创建字典后,我试图使用if语句更改列表中前3个元素的属性。然后打印列表中的前6个元素以检查是否应用了更改

properties1={'color':'silver','weight':45,'Height':5.5,'planet':'mars'}
for alien in range(30):
    aliens.append(properties1)
for alien in aliens[0:3]:
    if alien['color'] == 'silver':
        alien['weight']=10
        alien['Height']=2
        print(alien)
for alien in aliens[:6]:
    print(alien)
输出为

{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}

你只有一本字典,在你的列表中你引用了30次。你所更新的任何东西都会更新这一条,所以你所有的外星人都是一样的

您应该在第一个循环中附加此dict(
properties1.copy()
的副本,而不是properties1:

properties1={'color':'silver','weight':45,'Height':5.5,'planet':'mars'}
aliens = []
​
for alien in range(30):
    aliens.append(properties1.copy())
for alien in aliens[0:3]:
    if alien['color'] == 'silver':
        alien['weight']=10
        alien['Height']=2
        print(alien)
for alien in aliens[:6]:
    print(alien)
输出:

{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 10, 'Height': 2, 'planet': 'mars'}
{'color': 'silver', 'weight': 45, 'Height': 5.5, 'planet': 'mars'}
{'color': 'silver', 'weight': 45, 'Height': 5.5, 'planet': 'mars'}
{'color': 'silver', 'weight': 45, 'Height': 5.5, 'planet': 'mars'}

嗨,你能添加一些输出吗?还有,这是所有的代码吗?
外星人
列表的声明不在这里。是否可以提供关于这个问题的更多信息?你的问题不清楚。无论如何,请注意,你只有一本字典,在你的列表中引用了30次。你更新的任何东西都会更新这一条字典,所以所有人都会更新您
alien
将是同一个。您应该附加
属性1.copy()
而不是第一个循环中的
属性1
。@JorgeMorgado输出被添加dict列表和列表列表出现相同的问题。是的,我现在知道了。我不知道所做的更改会影响原始词典。我想更改只会影响我正在使用的词典列表中的项目重复。抱歉,如果你不懂我的英语。顺便说一句,谢谢你的信息