1

i tried to create a for loop that can change the value of dictionary 'title'. The new value will be then appended to the b list. So there will be 5 dict in b list with different 'title' value. This is my code.

dictionary = {'title': 'hello', 'black': 'white', 'yellow':'green'}
b = []
for a in range(5):
    dictionary['title'] = str(a)
    b.append(dictionary)
print b

The result is:

[{'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}, {'black': 'white', 'yellow': 'green', 'title': '4'}]

[Finished in 0.136s]

Why all of the 'title' have the same value? How can I get a different number for each dicts appended to the list. Thanks

2
  • 1
    You have just one dictionary, duplicated across your list Commented May 9, 2017 at 14:24
  • Just use a print b inside the loop, You will understand everything. Commented May 9, 2017 at 14:26

2 Answers 2

3

When you are appending dictionary, you are actually appending its reference since dictionaries are mutable - that's why all of the entries are actually pointing to a single copy of the dictionary. Use it's copy method to append a copy of it instead of the original:

b.append(dictionary.copy())
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, I didn't know that it is mutable.
0

You keep appending the same dictionary (note that they don't all just have the same value, but the last value that element was set to); if you want them to be different, you have to make a new dictionary for each appending.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.