Create dict key only when needed
Helge Stenstrom
helge.stenstrom.NO at SPAM.ericsson.com
Thu Feb 13 08:55:33 EST 2003
I'd like to do the following, which doesn't work:
a = {}
for key in keys:
a[key] += stringFunction()
where keys contains some duplicates. Put in another way:
a = {}
a[17] += "foo"
a[4711] += "foo"
a[4711] += "bar"
would give a = {17: "foo", 4711: "foobar"}
but that doesn't work, because the keys of the dict must exist before
the += operator can be used.
How can this problem be solved in a readible way?
An ugly solution would be:
# -------- Start of example ---------
def addStuff(dict, key, data):
if dict.has_key(key):
dict[key] += data
else:
dict[key] = data
# =========== UNIT TEST ==========
import unittest
class Ok(unittest.TestCase):
def test1(self):
a = {}
addStuff(a, 17, "foo")
addStuff(a, 4711, "foo")
addStuff(a, 4711, "bar")
self.assertEqual(a, {17: "foo", 4711: "foobar"})
if __name__ == '__main__':
unittest.main()
# -------- End of example ---------
How can the += syntax be used instead of calling a function?
Cheers,
Helge
More information about the Python-list
mailing list