Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing dictionary path in Python

Brand new to python, Let's say I have a dict:

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

If child3 changes their hair colour regularly, I might want to write an application to speed up the data maintenance. In this example i'd use:

kidshair['allkids']['child3']['hair'] = ...

Is there any way to store this path as a variable so I can access it at my leasure? Obviously

mypath = kidshair['allkids']['child3']['hair']

results in mypath = 'red'. Is there any possible way to hard code the path itself so I could use:

mypath = 'blue' 

to reperesent

kidshair['allkids']['child3']['hair'] = 'blue'

Kind thanks, ATfPT

like image 605
Dom Vinyard Avatar asked Apr 29 '12 11:04

Dom Vinyard


1 Answers

You can save a reference to kidshair['allkids']['child3'] easily:

thiskid = kidshair['allkids']['child3']
thiskid['hair'] = 'blue'

You can't save the entire path, because the assignment changes the hair key in the kidshair['allkids']['child3'] dictionary.
If you want to change a dictionary, you must have a reference to it, not to something it contains.

like image 94
ugoren Avatar answered Oct 26 '22 00:10

ugoren