Randomblue
Randomblue

Reputation: 116403

Adding elements to a dictionary of sets

I have a dictionary d of sets. When adding an element under some key key I consider the two cases key in d and not key in d:

from random import randint

for i in range(1000):
    key = randint(0, 100)

    if key in d:
        d[key] |= set([randint(0, 10)])
    else:
        d[key] = set([randint(0, 10])

Is there a cleaner way to do this? Can I unify the two cases?

Upvotes: 2

Views: 259

Answers (2)

inspectorG4dget
inspectorG4dget

Reputation: 114035

Try [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict)s: from collections import defaultdict

A defaultdict takes a "default factory" parameter. Basically, it lets you set a default value for keys that haven't been "initialized" yet.

So in your example, you wouldn't have to do the if el in d check, if d is a defaultdict. While that check would still return False, doing d[el] |= set([randint(0, 10)]) would essentially result in the following, if el wasn't already in d:

d[el] = set([])
d[el] |= set([randint(0, 10)])

Hope this helps

Upvotes: 0

DSM
DSM

Reputation: 353499

I like using a defaultdict, which is a kind of dictionary which creates a default object when you refer to a key which isn't yet defined:

>>> from random import randint
>>> from collections import defaultdict
>>> 
>>> d = defaultdict(set)
>>> 
>>> for i in range(10):
...     el = randint(0, 5)
...     d[el].add(randint(0,10))
... 
>>> d
defaultdict(<type 'set'>, {0: set([2]), 1: set([7]), 2: set([8, 9, 5, 7]), 
3: set([1]), 4: set([1, 3, 4])})
>>> d[0]
set([2])
>>> d[2]
set([8, 9, 5, 7])

Upvotes: 5

Related Questions