python change a key in a dictionary code example

Example 1: python change a key in a dictionary

# Basic syntax:
# Approach 1:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

# Approach 2:
dictionary[new_key] = dictionary.pop(old_key)

Example 2: change dictionary value python

my_dict  =  {
   'foo': 42,
   'bar': 12.5
}
my_dict['foo']  =  "Hello"
print(my_dict['foo'])
#This will give the output:

'Hello'

Example 3: replace key of dictionary python

a_dict = {"a": 1, "B": 2, "C": 3}

new_key = "A"
old_key = "a"
a_dict[new_key] = a_dict.pop(old_key)

print(a_dict)
OUTPUT
{'B': 2, 'C': 3, 'A': 1}

Example 4: change key of dictionary python

>>> 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

Tags:

Misc Example