Reputation: 41
I have a dictionary where key is a tuple (class,word). I want to initialize the value of dictionary for a particular class, irrespective of the word to a particular default value. Eg: dict = defaultdict(lambda : -1.0)
dict [('A', any word here)] = some constant value according to lambda expression
Here of the tuple ('A', any word here)- A is the class while "any word here" can be any random unknown word. This was my attempt, but am unable to figure out the correct way: dict = defaultdict(lambda tag, x: some_constant)).
How to I make x a placeholder that might come in its place?
Upvotes: 2
Views: 2397
Reputation: 113924
As I understand it, you want a dictionary to have a default value that depends on part of the key. If so, I think this does what you want:
class MyDict(dict):
def __missing__(self, key):
class_, word = key
self[key] = class_ # Replace this with what you want
return self[key]
Now, MyDict
behaves just as a normal dictionary except that missing values are filled in according to the custom function which you will have to adjust to your needs.
For example:
In [22]: d = MyDict()
In [23]: d[(int, 'delta')]
Out[23]: int
In [24]: d[(str, 'gamma')]
Out[24]: str
In [25]: d
Out[25]: {(str, 'gamma'): str, (int, 'delta'): int}
Be careful of one point: when you use the get
attribute to a dictionary with a missing key, it will not call __missing__
. Instead, it will return whatever you specify as the second argument to get
and that defaults to None
.
defaultdict
One might like defaultdict
to behave as you want with:
dict = defaultdict(lambda tag, x: some_constant))
However, this will not work because the defaultdict
constructor does not accept arguments. With defaultdict
, the default value must be the same regardless of key.
Upvotes: 3