Armido Maamägi
Armido Maamägi

Reputation: 95

Python dictionary append

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)

Upvotes: 6

Views: 83896

Answers (2)

Jonas
Jonas

Reputation: 1573

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.

Upvotes: 9

TigerhawkT3
TigerhawkT3

Reputation: 49320

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.

Upvotes: 1

Related Questions