By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,923 Members | 1,655 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,923 IT Pros & Developers. It's quick & easy.

Updating values in nested dictionary

P: 1
I'm looking for a way to update a nested dict dict1
dic1 = {'key1': {'key2': {'key3': {'key4': {'key51': {'key511': 'val511', 'key512': 'val512'}}, 'key52': {'key521': {'key5211': 'val5211', 'key5212': 'val5212'}}}}}}

I want to replace the element in dic1: {'key51': {'key511': 'val511', 'key512': 'val512'}} to 'val4'

So I can get a new dictionary as the following:
dic2 = {'key1': {'key2': {'key3': {'key4': 'val4', 'key52': {'key521': {'key5211': 'val5211', 'key5212': 'val5212'}}}}}}

I can do this manually using the following statement

>>> dic1['key1']['key2']['key3']['key4'] = 'val4'
Expand|Select|Wrap|Line Numbers
  1. >>> dic1
  2. {'key1': {'key2': {'key3': {'key52': {'key521': {'key5211': 'val5211', 'key5212': 'val5212'}}, 'key4': 'val4'}}}}
but I got stuck in writing Python code for this problem

Your help would be very much appreciated. Thank you.
Oct 19 '11 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 2.5K+
P: 2,851
The way you updated the dictionary manually would be the way to do it. What about writing code for it is a problem? Are you trying to copy the dictionary and change a value?
Oct 19 '11 #2

Expert 100+
P: 624
When a dictionary is nested more than one or two levels deep, you should consider using SQLite instead
Oct 23 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.