[Tutor] dictionary append

bob gailer bgailer at alum.rpi.edu
Thu Nov 1 23:52:08 CET 2007


Dinesh B Vadhia wrote:
> Hello!  I'm creating a dictionary called keywords that has multiple 
> entries each with a variable list of values eg.
>  
> 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. 
Please show us the lines in the file that led to that outcome.

Your program starts with k == 0. That suggests there should be a 
keywords[0] entry.
> For each key, the value is append'ed until the next key.  Here is the 
> code.
>  
> ..............
> >>> keywords = {}
> >>> with open("x.txt", "r") as f:
>     k=0
>     for line in f.readlines():
>             keywords[k], second = map(int, line.split())
>             keywords[k].append(second)
>            if keywords[k] != k:
>                    k=k+1
>    
> Traceback (most recent call last):
>   File "<pyshell#44>", line 5, in <module>
>     keywords[k].append(second)
> AttributeError: 'int' object has no attribute 'append'
> ..............
>  
> Any idea why I get this error?
Yes, and I'm surprised you have no idea! I say surprised, because a long 
time ago I learned to "walk through" my code line by line and write down 
what was happening. If you do that you should note that:

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

creates 2 integer values, and assigns the first to keywords[0]. Then you 
try to use:

            keywords[k].append(second)

to append the second integer to the first. As the message says, "'int' 
object has no attribute 'append'". append requires a list-like object.

Since your results seem incorrect anyway it is hard to diagnose. So 
please show us the input.

Also note that if you fix it so each dict entry is a list-like object, 
then keywords[k] != k will always be false, as that is comparing a list 
to an int.

Alan suggested creating a list using [first], but that only works for 
the first occurrence of each new key.

If this were my program, I'd guess that the input file looks like key, 
value pairs:

1 1
1 4
1 6
1 3
2 67
2 2
3 2
3 8
3 5
3 66
3 3
3 23

Is that accurate?

If so my program would be:

keywords = {}
for line in file("x.txt", "r"):
    key, value = map(int, line.split())
    if key not in keywords:
       keywords[key] = []
    keywords[key].append(value)

 HTH



More information about the Tutor mailing list