1

This post from 2012 provides a (possible) solution where an entry in the dictionary

my_dict = {'allkids':{'child1':{'hair':'blonde'},
                      'child2':{'hair':'black'},
                      'child3':{'hair':'red'},
                      'child4':{'hair':'brown'}}}

can be accessed using

mypath = ('allkids', 'child3', 'hair')
kidshair[mypath]

However, I get a KeyError: ('allkids', 'child3', 'hair') in the kidshair[mypath] line when trying this (using Python 3.9.7).

I would like to use a similar solution to set the value of an entry located at a given path. I specifically don't want a function to do that:

kidshair[mypath] = 'black' # this is what I want

set_value(dict=kidshair, path=mypath, value='black') # this is what I don't want

kidshair = set_value(dict=kidshair, path=mypath, value='black') # neither do I want this

I need to set the values programmatically. So given a dictionary and a path, how do I perform an operation similar to my_dict['allkids']['child1']['hair'] = 'Black'?

Hein Schnell
  • 322
  • 5
  • 15
  • 1
    Why not just `kidshair['allkids']['child3']['hair'] = 'yourValue'`? – Thijmen Nov 15 '21 at 10:54
  • 1
    @Thijmen yea i don'se see why ```my_dict['allkids']['child1']['hair'] = 'Black'```wont' t work? – pyzer Nov 15 '21 at 10:56
  • @Thijmen @pyzer Ah, good point. I would like to access the values programmatically. So given a dictionary and a path, how do I perform an operation similar to `my_dict['allkids']['child1']['hair'] = 'Black'`. – Hein Schnell Nov 15 '21 at 11:06
  • 1
    Just use variables instead of strings: `mychild = "child1" myproperty = "hair" my_dict["allkids"][mychild][myproperty] = "Black"` – gimix Nov 15 '21 at 11:10
  • Hey thanks for the input. You are right. Somehow I didn't catch the obvious solutions. – Hein Schnell Nov 15 '21 at 12:14

0 Answers0