简体   繁体   中英

Python change a value of a dictionary with a list of keys

I have a dictionary, like this:

myDict = {"a":{"a":{"a":8, "b":4, "c":5}, "b":{"a":0, "b":2, "c":1}, "c":{"a":3, "b":9, "c":6}}}

and I have a list (with multiple element, it can be so much):

myKeys = ["a", "c", "b"]

and my problem is, that I want to make a function that change the value of the dictionary:

def ValKeys(mDict, mKeys, mValue):
   #some code...
   #it do that:
   mDict[mKeys[0]][mKeys[1]][mKeys[2]]...[mKeys[len(mKeys)]] = mValue
   return mDict

for example in this case, it returns:

myDict = ValKeys(myDict, myKeys, 7) #=> myDict["a"]["c"]["b"] = 7 (instead of 9)

I guess the biggest problem is that you don't know the length of mKeys , but you can use a loop to access nested dict :

def ValKeys(mDict, mKeys, mValue):
    tmp_dict = mDict
    for k in mKeys[:-1]:  # notice we stop before last key
        tmp_dict = tmp_dict[k]
    # now tmp_dict is the reference for the most nested dict, we can just assign value
    tmp_dict[mKeys[-1]] = mValue

mDict = {"a": {"b": 1}}
mKeys = ["a", "b"]

ValKeys(mDict, mKeys, 5)
print(mDict) # {"a": {"b": 5}}

And the same with more pythonic approach:

import functools

def ValKeys(mDict, mKeys, mValue):
    nested = functools.reduce(lambda d, x: d[x], mKeys[:-1], mDict)
    nested[mKeys[-1]] = mValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM