如何将新对象添加到嵌套字典?

时间:2015-05-15 11:05:13

标签: python nested

鉴于以下对象,如何在“加利福尼亚”中添加新城市“losangeles”?给定城市的国家,州,城市和属性,我该如何更新对象? (我对python很新)

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中完成的那样):

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

编辑: 这不是重复的。我正在寻找一种添加项目的通用方法。

3 个答案:

答案 0 :(得分:3)

你几乎得到了它 -

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

答案 1 :(得分:1)

您可以使用具有默认值树的字典创建树:

>>> from collections import defaultdict

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


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

答案 2 :(得分:0)

尝试:

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