Help needed : Dictionary tricks in 2.2

Jason Orendorff jason at jorendorff.com
Mon Jan 14 09:41:34 EST 2002


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

Eh, not really.  Dictionaries are implemented using hashtables, so
their data structure inherently *can't* be sorted.

But you can overload keys(), values(), and items() to
automatically sort each time they're called.


> 2) The following code turns list (or tuple) into dictionary fast 
> (without doubles):
> 
> 	>>> 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': ""}

for x in l:
    d[x] = ""

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list