0

hey i was trying to to change the elements in the dictionary using the if statement in a for loop , when i include the properties dictionary in the first for loop , it seems to be working fine. otherwise i cant change the elements as i desired .

what i was trying to do is , creating an empty list . then adding 30 dictionary items with same attributes. after the dictionary is created , i was trying to change the attributes of first 3 elements in the list using a if statement . then printing the first 6 elements in the list to check whether the change is applied or not

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)

output is

{'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'}

1 Answers1

0

You have only one dictionary, that you reference 30 times in your list. Anything you update will update this one dict, so all you alien will be one and the same.

You should append a copy of this dict (properties1.copy() instead of properties1 in your first loop:

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)

Output:

{'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'}
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • yea , i got it now . i was not aware that the changes made will affect the original dictionary. i was thinking the change will only affect the items in the list of dictionary that i'm iterating . sorry if you dont understand my english. btw thanks for the info – Abhishek N Oct 04 '20 at 06:58