Help needed : Dictionary tricks in 2.2
pekka niiranen
krissepu at vip.fi
Mon Jan 14 03:55:01 EST 2002
Two questions:
1) In Guido's tutorial he created a new dictionary as follows:
class defaultdict(dict):
def __init__(self, default=None):
dict.__init__(self)
self.default = default
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.default
def merge(self, other):
for key in other:
if key not in self:
self[key] = other[key]
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 ???
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': ""}
-pekka-
More information about the Python-list
mailing list