[Tutor] Dictionary and List Question?

Clay Shirky clay at shirky.com
Wed Nov 12 21:32:29 EST 2003

After seeing how unpythonic my regex-laden string manipulations were (thanks
to Messrs. Kuchling and Speno!), I have two questions about pythonic
handling of a dictionary later transformed into a list.

I'm counting lines in a logfile and making each line a key in a dictionary,
so I can get the unique lines, but increment a counter. Later, I want to put
the lines in the list, in the form

17 /writings/spam.html
19 /writings/eggs.html

The first question is about the best way to increment the dictionary every
time I see the same line.

Right now I have

if entry in list:
    list[entry] += 1
    list[entry] = 1

but this seems verbose. Is there a way I can say, in one line "increment the
value of list[entry], even if its the first time you've seen entry"?

Next, I want to loop through the dictionary list, and take each key-value
pair, and turn them into a string of value-key, so that the number is first,
and then the line. Then I want to sort them so that the lines appear in
numerical order.

However, when I do this

for k, v in list.items():
    v = str(v)
    url_line = space.join( (v, k) )


the sort order of output puts the lines in the 1, 12, 13, 2, 21, 3 order,
which is to say an alpha sort of numeric strings. How do I get output.sort()
to sort in numeric order, even though I had to transform the numerical
values from the dictionary to strings to make them a single element in the



More information about the Tutor mailing list