pythondictionary

Change the name of a key in dictionary


How do I change the key of an entry in a Python dictionary?


Solution

  • Easily done in 2 steps:

    dictionary[new_key] = dictionary[old_key]
    del dictionary[old_key]
    

    Or in 1 step:

    dictionary[new_key] = dictionary.pop(old_key)
    

    which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key].

    >>> dictionary = { 1: 'one', 2:'two', 3:'three' }
    >>> dictionary['ONE'] = dictionary.pop(1)
    >>> dictionary
    {2: 'two', 3: 'three', 'ONE': 'one'}
    >>> dictionary['ONE'] = dictionary.pop(1)
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
    KeyError: 1