[Tutor] Dictionary and List Question?

Lloyd Kvam pythontutor at venix.com
Thu Nov 13 09:39:21 EST 2003


Clay Shirky wrote:

> if entry in list:
>     list[entry] += 1
> else:
>     list[entry] = 1
I think your naming could be improved.  list is used by python for
the list type.  Using list as a variable name prevents you from
calling the list type.  In addition, list is really a dictionary.

I'll use d_lines instead of list for my code snippet.

d_lines[entry] = d_lines.setdefault(entry, 0) + 1

setdefault will create the dictionary entry with an initial value,
zero in this case.  Then we always add one to count each line reference.

http://www.brunningonline.net/simon/python/PQR.html
Python Quick Reference

This is a real handy reference for looking up functions and methods.  (I've
downloaded the relevant version for me to minimize the load on their server.)

> 
> 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.

You can sort a list of tuples as well as strings.

l_lines = [(v,k) for (k,v) in d_lines.items()]
l_lines.sort()	# v is still a number so it will sort correctly

Now you can turn the sorted list of counts and lines into strings for output.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list