1

Given the below object, how to add a new city "losangeles" in "california"? Given a country, state, city and attributes for the city, how can I update the object? (I am pretty new to 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"]
      }
    }
  }
}

I tried adding elements as below (like how it is done in PHP):

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

Edit: This is not a duplicate. I am looking for a generic way to add items.

softwarematter
  • 28,015
  • 64
  • 169
  • 263

3 Answers3

3

You've almost got it -

myplaces['unitedstates']['california']['losangeles'] = {'description':'Entertainment'}
kaz
  • 1,190
  • 8
  • 19
2

You could create a tree using a dictionary with a default value of a tree:

>>> from collections import defaultdict

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


>>> myplaces = tree()
>>> myplaces['unitedstates']['california']['losangeles']['description'] = 'Entertainment'
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Try:

myplaces['unitedstates']['california']['losangeles']={}
myplaces['unitedstates']['california']['losangeles']['description']='Entertainment'
laila
  • 1,009
  • 3
  • 15
  • 27