2

I need to change values in a nested dictionary. Consider this dictionary:

stocks = {
        'name': 'stocks',
        'IBM': 146.48,
        'MSFT': 44.11,
        'CSCO': 25.54,
        'micro': {'name': 'micro', 'age': 1}
    }

I need to loop through all the keys and change the values of all the name keys.

stocks.name
stocks.micro.name

These keys need to be changed. But, I will not know which keys to change before hand. So, I'll need to loop through keys and change the values.

Example

change_keys("name", "test")

Output

{
     'name': 'test',
     'IBM': 146.48,
     'MSFT': 44.11,
     'CSCO': 25.54,
     'micro': {'name': 'test', 'age': 1}
}
4
  • 2
    "But, I will not know which keys to change before hand" Didn't you say you need to change all the "name" keys? Commented May 14, 2018 at 19:01
  • @DeepSpace yes thats right. That is just an example because there are multiple keys named 'name'. How would I ensure the correct value is changed? Commented May 14, 2018 at 19:03
  • Can you add an example of what input/output you expect? It's not clear how you want this dict mutated. Commented May 14, 2018 at 19:05
  • I gave a sample output Commented May 14, 2018 at 19:12

2 Answers 2

4

A recursive solution that supports unknown number of nesting levels:

def change_key(d, required_key, new_value):
    for k, v in d.items():
        if isinstance(v, dict):
            change_key(v, required_key, new_value)
        if k == required_key:
            d[k] = new_value

stocks = {
    'name': 'stocks',
    'IBM': 146.48,
    'MSFT': 44.11,
    'CSCO': 25.54,
    'micro': {'name': 'micro', 'age': 1}
}


change_key(stocks, 'name', 'new_value')
print(stocks)
#  {'name': 'new_value', 
#  'MSFT': 44.11, 
#  'CSCO': 25.54,
#  'IBM': 146.48,
#  'micro': {'name': 'new_value', 
#            'age': 1}
#  }
Sign up to request clarification or add additional context in comments.

Comments

2
def changeKeys(d, repl):
    for k,v in zip(d.keys(),d.values()):
        if isinstance(v, dict):
            changeKeys(v,repl)
        elif k == "name":
            d[k]= repl

6 Comments

zip(d.keys(),d.values())? WTF? d.items()!
I change where the key is 'name' into the value he wants, right?
@Attersson Not really
v= repl should be d[k] = repl, otherwise you're changing v which is just the value of value, rather than what is stored in the dict (when the item is immutable, like a string)
Dont change the keys. I just want the values changed. As illustrated in the sample output in the question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.