Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary that defaults to key?

Tags:

Is there a way to get a defaultdict to return the key by default? Or some data structure with equivalent behavior? I.e., after initializing dictionary d,

>>> d['a'] = 1 >>> d['a'] 1 >>> d['b'] 'b' >>> d['c'] 'c' 

I've only seen default dictionaries take functions that don't take parameters, so I'm not sure if there's a solution other than creating a new kind of dictionary .

like image 238
beardc Avatar asked May 29 '12 00:05

beardc


People also ask

Can Python dictionary set key?

Is it safe to use a frozenset as a dict key? Yes. According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.

Can dictionary have set as key?

These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.

Can you set a default value for dictionary Python?

It turns out that in Python there is no good way to set a default value of a dictionary.

What is the default value of a key in dictionary?

default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError .


1 Answers

I'd override the __missing__ method of dict:

>>> class MyDefaultDict(dict): ...     def __missing__(self, key): ...         self[key] = key ...         return key ... >>> d = MyDefaultDict() >>> d['joe'] 'joe' >>> d {'joe': 'joe'} 
like image 197
pillmuncher Avatar answered Oct 21 '22 22:10

pillmuncher