In [1]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d['k1']
del d['k1']
print(d)
In [2]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
print(d.pop('k1'))
In [3]:
print(d)
In [4]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
d['k10'] = d.pop('k1')
print(d)
In [5]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
# print(d.pop('k10'))
# KeyError: 'k10'
In [6]:
print(d.pop('k10', None))
In [7]:
print(d)
In [8]:
def change_dict_key(d, old_key, new_key, default_value=None):
d[new_key] = d.pop(old_key, default_value)
In [9]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key(d, 'k1', 'k10')
print(d)
In [10]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key(d, 'k10', 'k100')
print(d)
In [11]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key(d, 'k10', 'k100', 100)
print(d)
In [12]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key(d, 'k1', 'k2')
print(d)
In [13]:
def change_dict_key_setdefault(d, old_key, new_key, default_value=None):
d.setdefault(new_key, d.pop(old_key, default_value))
In [14]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_setdefault(d, 'k1', 'k2')
print(d)
In [15]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_setdefault(d, 'k1', 'k10')
print(d)
In [16]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_setdefault(d, 'k10', 'k100')
print(d)
In [17]:
def change_dict_key_exist(d, old_key, new_key):
if old_key in d:
d[new_key] = d.pop(old_key)
In [18]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_exist(d, 'k1', 'k10')
print(d)
In [19]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_exist(d, 'k10', 'k100')
print(d)
In [20]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_exist(d, 'k1', 'k2')
print(d)
In [21]:
def change_dict_key_exist_setdefault(d, old_key, new_key):
if old_key in d:
d.setdefault(new_key, d.pop(old_key))
In [22]:
d = {'k1': 1, 'k2': 2, 'k3': 3}
change_dict_key_exist_setdefault(d, 'k1', 'k2')
print(d)