Python Forum
How to change value in a nested dictionary? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to change value in a nested dictionary? (/thread-21294.html)



How to change value in a nested dictionary? - nzcan - Sep-23-2019

I have a dictionary whose keys are strings and the values are other, nested dictionaries.
The values ( nested dictionaries ) have different numbers of items. From 2 to 33.
How can I change a certain value of a certain nested dictionary that have 25 items without rewriting the nested dictionary manually by using for example:

nested_dict_1['user-1'] = 'sky'
the dictionary looks like this:
prime_dict = {'user-1': {'cars': 3, 'byckes': 8, 'bus-tickets': 27, 'shoes': 48}, 
              'user-2': {'appels': 2, 'babanas':7, 'limo':11, 'peaches': 9, 'mellons': 11, 'grapps': 31, 'potatos': 38}}
I want to change the value 11 to 15 for the key 'limo' in the nested dictionary that is a part of the value to the key 'user-2'.
How can I do this without to rewrite manually the hole value of the key 'user-2'?



RE: How to change value in a nested dictionary? - ichabod801 - Sep-23-2019

prime_dict['user-2']['limo'] = 15
A way to think about it: prime_dict['user-2'] gives you the sub-dictionary {'appels': 2, 'babanas':7, 'limo':11, 'peaches': 9, 'mellons': 11, 'grapps': 31, 'potatos': 38}, and then ['limo'] allows you to change the appropriate value.


RE: How to change value in a nested dictionary? - nzcan - Sep-23-2019

(Sep-23-2019, 02:54 PM)ichabod801 Wrote:
prime_dict['user-2']['limo'] = 15
A way to think about it: prime_dict['user-2'] gives you the sub-dictionary {'appels': 2, 'babanas':7, 'limo':11, 'peaches': 9, 'mellons': 11, 'grapps': 31, 'potatos': 38}, and then ['limo'] allows you to change the appropriate value.

Super! Thanks a lot!