[Tutor] dictionary append

Alan Gauld alan.gauld at btinternet.com
Thu Nov 1 23:14:56 CET 2007


"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote

keywords[1] = [1, 4, 6, 3]
keywords[2] = [67,2]
keywords[3] = [2, 8, 5, 66, 3, 23]
etc.

The keys and respective values (both are integers) are read
in from a file.  For each key, the value is append'ed until
the next key.  Here is the code.

.............
>>> keywords = {}
>>> with open("x.txt", "r") as f:

You don;t need the with statement for this, just do

for line in open('x.txt'):

            keywords[k], second = map(int, line.split())

So keywords[k] and second are both ints

            keywords[k].append(second)

But you can't append to an int.
Try creating a temp value first:

            first, second = map(int, line.split())
            keywords[k] = [first]  # creates a list value instead of 
an int
            keywords[k].append(second)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list