Help needed : Dictionary tricks in 2.2
Martin von Loewis
loewis at informatik.hu-berlin.de
Mon Jan 14 04:58:06 EST 2002
pekka niiranen <krissepu at vip.fi> writes:
> Q1: Is it possible to add a method that would sort dictionary in place:
>
> def sortme(self):
> keys = self.keys()
> keys.sort()
> AND NOW WHAT ???
No. A dictionary is not inherently sorted. If you want some sorting,
you'll need to redefine the appropriate methods, like
def keys(self):
k = super(defaultdict,self).keys()
k.sort()
return k
That, of course, will not affect the return value of .items(), or the
iterators.
> >>> d = {}
> >>> l = ['a','b','c','b']
> >>> dummy = map(operator.setitem, [d]*len(l), l, [])
> >>> d
> {'a': None, 'c': None, 'b': None}
>
> Q2: How can I modify the code to create dictionary with
> empty string -values instead of None's
>
> {'a': "", 'c': "", 'b': ""}
Try
dummy = map(d.__setitem__, l, [""]*len(l))
HTH,
Martin
More information about the Python-list
mailing list