[Tutor] Dictionary and List Question?

John P Speno speno at isc.upenn.edu
Wed Nov 12 22:41:36 EST 2003

On Wed, Nov 12, 2003 at 09:32:29PM -0500, Clay Shirky wrote:
> if entry in list:
>     list[entry] += 1
> else:
>     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"?

In python, it is better to ask forgivness than permission, so:

    list[entry] +=1
except KeyError:
    list[entry] = 1

I though that the dict's setdefault method might work here, but after
testing, I don't think it will. It's nice when you have a dict of lists,
like this:

    list.setdefault(key, []).append(value)

And the next problem:

> 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

You probably want to call sort with a customized comparision function.

Untested code follows:

l = []
l_append = l.append
for k, v in list.iteritems():
    l_append((v, k))

def my_sort(a, b):
    return cmp(a[0], b[0])


for x in l:
    output.append('%d %s' % x) 

Hope that helps.

More information about the Tutor mailing list