📜  Python|更改字典中的键的方法

📅  最后修改于: 2022-05-13 01:55:06.958000             🧑  作者: Mango

Python|更改字典中的键的方法

给定一个字典,任务是根据需求更改键。让我们看看我们可以完成这项任务的不同方法。

方法#1:使用朴素的方法

# 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))
输出:


方法 #2:使用pop()

# 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))
输出:


方法#3:使用 zip()

假设我们要更改字典的所有键。

# 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))
输出: