Suppose I have two dicts in Python:
mydict = { 'a': 0 } defaults = { 'a': 5, 'b': 10, 'c': 15 }
I want to be able to extend mydict using the default values ββfrom defaults , so that 'a' remains the same, but 'b' and 'c' are populated. I know about dict.setdefault() and dict.update() , but everyone does only half of what I want - with dict.setdefault() , I have to dict.setdefault() over each variable in defaults ; but with dict.update() , defaults will blow away any pre-existing values ββin mydict .
Is there some kind of functionality that I don't find built in to Python that can do this? And if not, is there a more pythonic way to write a loop to re-call dict.setdefaults() than this:
for key in defaults.keys(): mydict.setdefault(key, defaults[key])
Context: I write some data in Python, which controls how to parse an XML tree. There is a dict for each node (i.e. How to process each node), and I would prefer that the data I write is sparse, but filled by default. The sample code is just an example ... real code has many more key / value pairs in the standard dict.
(I understand that this whole question is just a minor pun, but it bothered me, so I was wondering if there is a better way to do this that I don't know about.)
python dictionary
Daniel Lew
source share