I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ?
Put it another way, I want the dict to return the specified default value for every key I didn't yet set.
Python dictionary setdefault() Method Python dictionary method setdefault() is similar to get(), but will set dict[key]=default if key is not already in dict.
Using fromkeys() function If you want to initialize all keys in the dictionary with some default value, you can use the fromkeys() function. If no default value is specified, the dictionary is initialized with all values as 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 .
In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values. In the above code first, we will initialize a dictionary and assign key-value pair elements.
You can replace your old dictionary with a defaultdict
:
>>> from collections import defaultdict >>> d = {'foo': 123, 'bar': 456} >>> d['baz'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'baz' >>> d = defaultdict(lambda: -1, d) >>> d['baz'] -1
The "trick" here is that a defaultdict
can be initialized with another dict
. This means that you preserve the existing values in your normal dict
:
>>> d['foo'] 123
Use defaultdict
from collections import defaultdict a = {} a = defaultdict(lambda:0,a) a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19} for k,v in results.iteritems(): a['count'] += v['count'] a['pass_count'] += v['pass_count']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With