Dado un diccionario, la tarea es cambiar la clave según el requisito. Veamos diferentes métodos con los que podemos hacer esta tarea.
Método #1: Usar un método ingenuo
Python3
# Python code to demonstrate # changing keys of dictionary # using naive method # inititialising dictionary ini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial json print ("initial 1st dictionary", ini_dict) # changing keys of dictionary ini_dict['akash'] = ini_dict['akshat'] del ini_dict['akshat'] # printing final result print ("final dictionary", str(ini_dict))
Producción
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Método #2: Usar pop()
Python3
# Python code to demonstrate # changing keys of dictionary # using pop() method # inititialising dictionary ini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # printing initial json print ("initial 1st dictionary", ini_dict) # changing keys of dictionary ini_dict['akash'] = ini_dict.pop('akshat') # printing final result print ("final dictionary", str(ini_dict))
Producción
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} final dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akash': 15}
Método #3: Usar zip() Supongamos que queremos cambiar todas las claves del diccionario.
Python3
# Python code to demonstrate # changing all keys of dictionary # corresponding to list using zip() # inititialising dictionary ini_dict = {'nikhil': 1, 'vashu' : 5, 'manjeet' : 10, 'akshat' : 15} # initialising list ini_list = ['a', 'b', 'c', 'd'] # printing initial json print ("initial 1st dictionary", ini_dict) # changing keys of dictionary final_dict = dict(zip(ini_list, list(ini_dict.values()))) # printing final result print ("final dictionary", str(final_dict))
Producción
initial 1st dictionary {'nikhil': 1, 'vashu': 5, 'manjeet': 10, 'akshat': 15} final dictionary {'a': 1, 'b': 5, 'c': 10, 'd': 15}
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA