Updating values in nested dictionary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • imas
    New Member
    • Oct 2011
    • 1

    Updating values in nested dictionary

    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'
    Code:
    >>> dic1
    {'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.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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?

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      When a dictionary is nested more than one or two levels deep, you should consider using SQLite instead http://www.wdvl.com/Authoring/python...s07162009.html

      Comment

      Working...