Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – create new list containing multiple dictionaries with the same key name and different value

I’m attempting to create a new list that contains an n number of dictionaries, each with the same key but different values, this has a very specific use case, so my initial idea is:

template = [
{'holder': None,},
]

event = []
for entry in range(0,4):
    event.extend(template)
    event[entry]['holder'] = "Mock-Value-" + str(entry)
    print(event[entry]['holder'])

print()
for item in event:
    print(item['holder'])

Based on the code above I’m expecting:

Mock-Value-0
Mock-Value-1
Mock-Value-2
Mock-Value-3

Mock-Value-0
Mock-Value-1
Mock-Value-2
Mock-Value-3

but instead I’m getting the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Mock-Value-0
Mock-Value-1
Mock-Value-2
Mock-Value-3

Mock-Value-3
Mock-Value-3
Mock-Value-3
Mock-Value-3

It’s obvious that I’m missing something here

Regards,
Yitzo

>Solution :

The reason why it seems that every element’s dictionary is tied to the last updated value is because they are all the same instance. This is because:

template = [
    {'holder': None,},
]

holds the same instance of dictionary that is created when these lines of code run. And your extending of the array:

event.extend(template)

pushes a pointer referencing the same instance into the list. Essentially, you end up with a list where each element points to the same instance. Thus, updating one of them (the last one in your case) updates the instance that all pointers are pointing to, resulting in it seeming like it changed all the other values when in fact, they are the same object.

A simple fix would be to create a new instance of the dictionary everytime by making it a function get_template instead:

get_template = lambda: [
    {'holder': None,},
]


event = []
for entry in range(0,4):
    event.extend(get_template())
    event[entry]['holder'] = "Mock-Value-" + str(entry)
    print(event[entry]['holder'])

print()
for item in event:
    print(item['holder'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading