关于python:如何向嵌套字典添加新对象?

How to add new objects to nested dictionary?

考虑到下面的对象,如何在"加利福尼亚"中添加一个新城市"洛杉矶"?给定城市的国家、州、市和属性,如何更新对象?(我对Python很陌生)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
myplaces = {
 "unitedstates": {
   "california": {
     "sanfrancisco": {
       "description":"Tech heaven",
       "population": 1234,
       "keyplaces": ["someplace1",
         "someplace2"]
      }
    }
  },
 "india": {
   "karnataka": {
     "bangalore": {
       "description":"IT hub of India",
       "population": 12345,
       "keyplaces": ["jpnagar",
         "brigade"]
      },
     "mysore": {
       "description":"hostoric place",
       "population": 12345,
       "keyplaces": ["mysorepalace"]
      }
    }
  }
}

我尝试如下添加元素(比如如何在PHP中完成):

1
myplaces['unitedstates']['california']['losangeles']['description'] = 'Entertainment'

编辑:这不是副本。我正在寻找添加项目的通用方法。


你快明白了-

1
myplaces['unitedstates']['california']['losangeles'] = {'description':'Entertainment'}


可以使用默认值为树的字典创建树:

1
2
3
4
5
6
7
8
>>> from collections import defaultdict

>>> def tree():
...     return defaultdict(tree)


>>> myplaces = tree()
>>> myplaces['unitedstates']['california']['losangeles']['description'] = 'Entertainment'


尝试:

1
2
myplaces['unitedstates']['california']['losangeles']={}
myplaces['unitedstates']['california']['losangeles']['description']='Entertainment'