I have trouble making my code work. I post only relevant part of the code.
File im using is in this page https://programmeerimine.cs.ut.ee/_downloads/lapsed.txt
First number is parent and 2nd his child. I also had different filed which translated numbers into name. (I made list ID_name it works fine i checked)
This other part of the code works fine except when I'm trying to add value to existing key.I get error AttributeError: 'str' object has no attribute 'append'
for line in f:
part=line.split(" ")
parent=part[0]
kid=part[1].strip()
for el in ID_name:
if parent == el[0]:
parent=el[1]
if kid == el[0]:
kid=el[1]
if parent not in parents.keys():
parents[parent]=kid
else:
parents[parent].append(kid)
The append function you're referencing only works for lists: https://docs.python.org/2/tutorial/datastructures.html
If you want to add a new key/value pair to a dictionary, use: dictionary['key'] = value
You can also opt for: dictionary.update({'key': value}), which works well for adding multiple key/value pairs at once.
You need to initialize a list rather than just adding the object. Change this:
parents[parent]=kid
to this:
parents[parent] = [kid]
This will give you a list to which you can append() new objects, rather than just a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With