Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value to all keys of a dict object in python?

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.

like image 508
Derrick Zhang Avatar asked Feb 04 '12 09:02

Derrick Zhang


People also ask

Can you set a default value for dictionary Python?

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.

How do you create a default value in a dictionary?

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 .

What is the default value of a key in dictionary Python?

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 .

How do you get all the keys values from a dict?

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.


2 Answers

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 
like image 181
Martin Geisler Avatar answered Sep 16 '22 15:09

Martin Geisler


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'] 
like image 35
Abhaya Avatar answered Sep 19 '22 15:09

Abhaya