Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set multiple defaults on a Python dict using another dict?

Suppose I've got two dicts in Python:

mydict = { 'a': 0 }

defaults = {
    'a': 5,
    'b': 10,
    'c': 15
}

I want to be able to expand mydict using the default values from defaults, such that 'a' remains the same but 'b' and 'c' are filled in. I know about dict.setdefault() and dict.update(), but each only do half of what I want - with dict.setdefault(), I have to loop over each variable in defaults; but with dict.update(), defaults will blow away any pre-existing values in mydict.

Is there some functionality I'm not finding built into Python that can do this? And if not, is there a more Pythonic way of writing a loop to repeatedly call dict.setdefaults() than this:

for key in defaults.keys():
    mydict.setdefault(key, defaults[key])

Context: I'm writing up some data in Python that controls how to parse an XML tree. There's a dict for each node (i.e., how to process each node), and I'd rather the data I write up be sparse, but filled in with defaults. The example code is just an example... real code has many more key/value pairs in the default dict.

(I realize this whole question is but a minor quibble, but it's been bothering me, so I was wondering if there was a better way to do this that I am not aware of.)

like image 251
Dan Lew Avatar asked May 11 '09 20:05

Dan Lew


People also ask

How do I change the default value in a dictionary?

Python Dictionary setdefault() Method Syntax: key – Key to be searched in the dictionary. default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.

Can a dictionary have another dictionary Python?

The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.

What is Setdefault () function?

The setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value, see example below.

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


1 Answers

If you don't mind creating a new dictionary in the process, this will do the trick:

newdict = dict(defaults)
newdict.update(mydict)

Now newdict contains what you need.

like image 98
DzinX Avatar answered Sep 29 '22 23:09

DzinX