Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the key in collections.defaultdict

collections.defaultdict is great. Especially in conjunction with lambda:

>>> import collections
>>> a = collections.defaultdict(lambda : [None,None])
>>> a['foo']
[None, None]

Is there a way to use the key given (e.g. 'foo') in the lambda? For example (doesn't work):

>>> a = collections.defaultdict(lambda : [None]*key)
>>> a[1]
[None]
>>> a[2]
[None, None]
>>> a
defaultdict(<function <lambda> at 0x02984170>, {1: [None], 2: [None, None]})
like image 975
Jonathan Livni Avatar asked Nov 01 '11 07:11

Jonathan Livni


People also ask

What is collections Defaultdict?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

What happens if you try to modify a key that doesn't exist in a Defaultdict?

A common problem that you can face when working with Python dictionaries is to try to access or modify keys that don't exist in the dictionary. This will raise a KeyError and break up your code execution.

How does Defaultdict work Defaultdict forces a dictionary?

A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError .

How do you check if a key exists in a dictionary Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.


1 Answers

You probably want __missing__ which is called on dict whenever you try to access an item not present in the dict; the vanilla __missing__ raises an exception, but you could do whatever you like in a subclass:

class A(dict):
    def __missing__(self, key):
        value = self[key] = [None] * key
        return value
like image 32
SingleNegationElimination Avatar answered Oct 19 '22 20:10

SingleNegationElimination