Overwrites dictionary values ​​for a loop in a list

Question

I made a for loop reading the contents of the list, however, assigning two values ​​to the dictionary, and then adding this output to the list, the next value overwrites everything in the list

Desired Result

I want to add several dictionaries to the list, so when I run the for loop and print everything connected with "ip", it will print all the values ​​associated with the value of the dictionary "ip".

code

device = { 'ip': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', } listofdevices = [] def begin(): file = open("outputfromterminal") contents = file.read() contents = contents.split(',')[1:] for x in contents: # do some text stripping x = x.split(' ') device['ip']=x[0] device['mac']=x[1] listofdevices.append(device) 

Code example

1st content index:

 x[0] = '10.10.10.1' x[1] = 'aa:bb:cc:dd' 

Second content index:

 x[0] = '20.20.20.1' x[1] = 'qq:ww:ee:ee:rr' 

What is really going on

  listofdevices[0] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr' listofdevices[1] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr' 
+5
source share
3 answers

Try this code. Each device tried to edit the same copy of the dictionary.

 listofdevices = [] def begin(): with open("outputfromterminal", 'r') as f: contents = f.read().split(',')[1:] for line in contents: # do some text stripping line = line.split(' ') device = { 'ip': line[0], 'mac': line[1], 'username': 'admin', 'password': [], 'device type': '', } listofdevices.append(device) 
+2
source

You do not create a new dictionary object each time. You just mutate the same object in each iteration. Try deep copying the dictionary using the copy module. Then, after receiving this copy, modify it and add it to the list:

 import copy device = { 'ip': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', } listofdevices = [] def begin(): file = open("outputfromterminal") contents = file.read() contents = contents.split(',')[1:] for x in contents: device = copy.deepcopy(device) #creates a deep copy of the values of previous dictionary. #device now references a completely new object # do some text stripping x = x.split(' ') device['ip']=x[0] device['mac']=x[1] listofdevices.append(device) 
0
source

The problem is with adding a list. When you add an item (in your case a dictionary). It does not create a dictionary, but it just puts a link.

It should work if you can initialize the dictionary each time in a for loop, so a new link is created.

 listofdevices = [] def begin(): file = open("outputfromterminal") contents = file.read() contents = contents.split(',')[1:] for x in contents: # do some text stripping x = x.split(' ') device = { 'ip': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', } device['ip']=x[0] device['mac']=x[1] listofdevices.append(device) 
0
source

Source: https://habr.com/ru/post/1274172/


All Articles