Home > OS >  Python - create new list containing multiple dictionaries with the same key name and different value
Python - create new list containing multiple dictionaries with the same key name and different value

Time:04-20

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:

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

CodePudding user response:

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'])
  • Related