Home > Net >  append dict to list and change value of dict
append dict to list and change value of dict

Time:10-12

I want to append a dictionary to a list. Thereafter, I would like to append the same dictionary to the list with one value changed in the dictionary. In the given example, I want to end up with a list of 2 dictionaries where one value is different from the other. However, when i try to accomplish this the value is changed in both dictionaries in the list. I am using the following example code:

details = []
string1 = 'I want some information from this string in a dictionary'
string2 = 'A short string'

row = {'first_word': string1.split(' ')[0],
       'last_word': string1.split(' ')[-1],
       'length_string': len(string1)}

details.append(row)

if len(string2) < 50:
    row['length_string'] = 'String2 is too short.'
    details.append(row)

for x in details:
    print(x)

This yields:

{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}

Changing the dict value updates the whole list it seems. I think I'm missing something obvious. Can someone please assist me with getting the below output?

{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 56}
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}

CodePudding user response:

Its because you are updating the same object! when you append the "row" to the list you are just passing the object id NOT the value. To get the desired result you have to create a second object (dictionary in this case) that will hold the new value. use:

new_row = row.copy()
new_row['length_string'] = "String2 is too short."
details.append(new_row)

CodePudding user response:

you can just use the copy function

from copy import copy

string1 = 'I want some information from this string in a dictionary'
string2 = 'A short string'

row = {'first_word': string1.split(' ')[0],
       'last_word': string1.split(' ')[-1],
       'length_string': len(string1)}

details = [row]

if len(string2) < 50:
    row2 = copy(row)
    row2['length_string'] = 'String2 is too short.'
    details.append(row2)

for x in details:
    print(x)
  • Related