Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

python - Updating nested dictionaries when data has existing key

I am trying to update values in a nested dictionary, without over-writting previous entries when the key already exists. For example, I have a dictionary:

  myDict = {}
  myDict["myKey"] = { "nestedDictKey1" : aValue }

giving,

 print myDict
>> { "myKey" : { "nestedDictKey1" : aValue }}

Now, I want to add another entry , under "myKey"

myDict["myKey"] = { "nestedDictKey2" : anotherValue }}

This will return:

print myDict
>> { "myKey" : { "nestedDictKey2" : anotherValue }}

But I want:

print myDict
>> { "myKey" : { "nestedDictKey1" : aValue , 
                 "nestedDictKey2" : anotherValue }}

Is there a way to update or append "myKey" with new values, without overwriting the previous ones?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a very nice general solution to dealing with nested dicts:

import collections
def makehash():
    return collections.defaultdict(makehash)

That allows nested keys to be set at any level:

myDict = makehash()
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue
myDict["myKey"]["nestedDictKey3"]["furtherNestedDictKey"] = aThirdValue

For a single level of nesting, defaultdict can be used directly:

from collections import defaultdict
myDict = defaultdict(dict)
myDict["myKey"]["nestedDictKey1"] = aValue
myDict["myKey"]["nestedDictKey2"] = anotherValue

And here's a way using only dict:

try:
  myDict["myKey"]["nestedDictKey2"] = anotherValue
except KeyError:
  myDict["myKey"] = {"nestedDictKey2": anotherValue}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...