Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the value of a node in a python dictionary by following a list of keys?

I have a bit of a complex question that I can't seem to get to the bottom of. I have a list of keys corresponding to a position in a Python dictionary. I would like to be able to dynamically change the value at the position (found by the keys in the list).

For example:

listOfKeys = ['car', 'ford', 'mustang']

I also have a dictionary:

DictOfVehiclePrices = {'car':
                          {'ford':
                              {'mustang': 'expensive',
                               'other': 'cheap'},
                           'toyota':
                              {'big': 'moderate',
                               'small': 'cheap'}
                          },
                       'truck':
                          {'big': 'expensive',
                           'small': 'moderate'}
                      }

Via my list, how could I dynamically change the value of DictOfVehiclePrices['car']['ford']['mustang']?

In my actual problem, I need to follow the list of keys through the dictionary and change the value at the end position. How can this be done dynamically (with loops, etc.)?

Thank you for your help! :)

like image 988
Leopold Joy Avatar asked Nov 20 '25 05:11

Leopold Joy


2 Answers

Use reduce and operator.getitem:

>>> from operator import getitem
>>> lis = ['car', 'ford', 'mustang']

Update value:

>>> reduce(getitem, lis[:-1], DictOfVehiclePrices)[lis[-1]] = 'cheap'

Fetch value:

>>> reduce(getitem, lis, DictOfVehiclePrices)
'cheap'

Note that in Python 3 reduce has been moved to functools module.

like image 128
Ashwini Chaudhary Avatar answered Nov 21 '25 19:11

Ashwini Chaudhary


A very simple approach would be:

DictOfVehiclePrices[listOfKeys[0]][listOfKeys[1]][listOfKeys[2]] = 'new value'
like image 26
sjs Avatar answered Nov 21 '25 19:11

sjs