pythondictionaryordereddict

How to replace existing key in a dictionary in python?


So , I have this code.
I want to replace the specific existing key at index 1 in a dictionary in python. Anyone have an idea on this?

from collections import OrderedDict
regDict= OrderedDict()
regDict[("glenn")] = 1
regDict[("elena")] = 2
print("dict",regDict)

prints:

dict OrderedDict([('glenn', 1), ('elena', 2)])

target output:

dict OrderedDict([('glenn', 1), ('new', 2)])  # replacing key in index 1  

Solution

  • Your approach towards making a dictionary is a little bit off. Let's start by making a new dictionary from two lists (one for keys and one for values):

    keys = ['a', 'b', 'c']
    vals = [1.0, 2.0, 3.0]
    
    dictionary = {keys[i]:value for i, value in enumerate(vals)}
    

    This gives us the following:

    {'a': 1.0, 'b': 2.0, 'c': 3.0}
    

    You can also go here for some more help with making dictionaries: Convert two lists into a dictionary

    To replace the 'a' key with 'aa', we can do this:

    new_key = 'aa'
    old_key = 'a'
    
    dictionary[new_key] = dictionary.pop(old_key)
    

    Giving us:

    {'b': 2.0, 'c': 3.0, 'aa': 1.0}
    

    Other ways to make a dictionary:

    dictionary = {k: v for k, v in zip(keys, values)}

    dictionary = dict(zip(keys, values))

    Where 'keys' and 'values' are both lists.