Python Forum

Full Version: updating a dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to python and am having a problem updating a dictionary. I'm trying to enter several key/value pairs in a dictionary, however it appears each update overwrites the previous addition. any one know where I'm going wrong on this?

          ...... 
          print ("tmp_dict before loop:    ", tmp_dict)
          for key, value in tmp_dict.items():
               cisco_vars.update({'interface': {notepad_str: {key: value}}})
               print('cisco_vars in  loop:  ' , cisco_vars,  "\n\n")

          print('cisco_vars after for loop:  ' , cisco_vars,  "\n\n")
          .......
sample output:
Output:
cisco_vars in loop: {'interface': {'FastEthernet1/0/1': {'trunk allowed vlan': ['7']}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars after for loop: {'interface': {'FastEthernet1/0/1': {'trunk allowed vlan': ['7']}}, 'hostname': 'CISCO-ANS-TEST', ....} tmp_dict before loop: {'portfast': True, 'network-policy': '15', 'mode': 'access', 'access_vlan': '144', 'description': 'ADMN-175B-1-2'} cisco_vars in loop: {'interface': {'FastEthernet1/0/2': {'portfast': True}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars in loop: {'interface': {'FastEthernet1/0/2': {'network-policy': '15'}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars in loop: {'interface': {'FastEthernet1/0/2': {'mode': 'access'}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars in loop: {'interface': {'FastEthernet1/0/2': {'access_vlan': '144'}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars in loop: {'interface': {'FastEthernet1/0/2': {'description': 'ADMN-175B-1-2'}}, 'hostname': 'CISCO-ANS-TEST', ....} cisco_vars after for loop: {'interface': {'FastEthernet1/0/2': {'description': 'ADMN-175B-1-2'}}, 'hostname': 'CISCO-ANS-TEST', ....}
final contents of cisco_vars before program termination:
Output:
{'interface': {'FastEthernet1/0/2': {'description': 'ADMN-175B-1-2'}}, 'hostname': 'CISCO-ANS-TEST', ....}
This is a class I wrote that I use all the time. Makes managing dictionaries (on the create side)
very easy:
It might be of interest: https://github.com/Larz60p/TrulyDynamicDictionary
(Feb-19-2020, 09:43 PM)evansmb Wrote: [ -> ]I'm trying to enter several key/value pairs in a dictionary, however it appears each update overwrites the previous addition.

Yes, this is the core feature of Python dictionary:

Quote:It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
/../
If you store using a key that is already in use, the old value associated with that key is forgotten.