0

I am trying to make a list of dictionaries in python. Why don't these three methods produce the same results?

A = [{}]*2
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print A

B = [{},{}]
B[0]['first_name'] = 'Tom'
B[1]['first_name'] = 'Nancy'
print B


C = [None]*2
C[0] = {}
C[1] = {}
C[0]['first_name'] = 'Tom'
C[1]['first_name'] = 'Nancy'
print C

this is what I get:

[{'first_name': 'Nancy'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
2
  • In the first case you are creating a list with two elements referenceing the same dict. Commented May 6, 2019 at 16:59
  • What do you expect? Dictionaries in Python are unordered. If you want to keep the keys ordered, take a look on collections.OrderedDict(). Commented May 6, 2019 at 17:04

2 Answers 2

3

Your first method is only creating one dictionary. It's equivalent to:

templist = [{}]
A = templist + templist

This extends the list, but doesn't make a copy of the dictionary that's in it. It's also equivalent to:

tempdict = {}
A = []
A.append(tempdict)
A.append(tempdict)

All the list elements are references to the same tempdict object.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense. Thank you!
0

Barmar has a very good answer why. I say you how to do it well :)

If you want to generate a list of empty dicts use a generator like this:

A = [{}for n in range(2)]
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print (A)

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.