-1
def interface():
    interface_list = ['first', 'second']
    temp_interface = []
    interface_status = {
        "name": "",
        } 
    for item in interface_list:
        interface_status['name'] = item
        temp_interface.append(interface_status)
    print(temp_interface)
    
interface()


I am expecting [{'name': 'first'}, {'name': 'second'}]

but I am getting this [{'name': 'second'}, {'name': 'second'}]

What am I doing wrong.

1 Answers1

1

What you are appending to your list is not a copy of the dictionary interface_status but the dictionary itself. Then when you run interface_status['name'] = 'second' you are changing the value on the dictionary (again, not making a copy of it with a different key-value pair).

Here is a simple example to show what I mean:

>>> d = {'name':'first'}
>>> l = []
>>> l.append(d)
>>> l
[{'name': 'first'}]
>>> d['name'] = 'second'
>>> l
[{'name': 'second'}]

You can see that when I change what is going on in my dictionary d, it changes what shows up inside of the list l because the whole dictionary is inside of l.

This seems be happening because when you run d['name'] = 'asdf' in that format, you are updating the value on the dictionary.

You could instead run it all like this to get what you want - you'll see that we just fully recreate the interface_status dictionary each time. (as a side note, probably want to avoid naming the function and the dictionary the exact same thing.

def interface_status():
    interface_list = ['first', 'second']
    temp_interface = []
    for item in interface_list:
        interface_status = {'name':item}
        temp_interface.append(interface_status)
    print(temp_interface)
    
interface_status()
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29