-2

How to access an element inside a nested dictionary in python?

    myfamily = {
      "child1" : {
        "name" : "Emil",
        "year" : 2004
      },
      "child2" : {
        "name" : "Tobias",
        "year" : 2007
      },
      "child3" : {
        "name" : "Linus",
        "year" : 2011
      }
    }
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
crazy
  • 11
  • 2
  • 3
    Does this answer your question? [Accessing value inside nested dictionaries](https://stackoverflow.com/questions/10399614/accessing-value-inside-nested-dictionaries) – jossefaz Jul 05 '20 at 05:15

4 Answers4

1

Indexing myfamily yields another dict, which you index like any other.

>>> myfamily["child1"]["name"]
'Emil'
chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can treat sub dictionaries just like a new dictionary

myfamily['child1']['year']
greenPlant
  • 482
  • 4
  • 16
0

You can easily access a child by using myfamily["child1"]
You can also access all keys by calling the keys() method on the myfamily variable

cocool97
  • 1,201
  • 1
  • 10
  • 22
0

If you'd like to access the elements of myfamily, you can refer to those as myfamily['child1'], and that will return:

{
    "name" : "Emil",
    "year" : 2004
}

If child1 was its own directory, you were refer to elements in that as child1['name'] or child1['year']. Extending that to myfamily['child1'], you can access elements in child1 by identifying the element you want, like myfamily['child1']['name'] or myfamily['child1']['year'].

Why doesn't myfamily[child1['name']] work? If we separate our pieces, child1['name'] contains Emil. Substitute that for child1['name'] in myfamily[child1['name']], and we have myfamily['Emil']. That element doesn't exist in the myfamily dictionary, and will fail.

ladygremlin
  • 452
  • 3
  • 14