Home > OS >  how to change key value in dictionary
how to change key value in dictionary

Time:07-16

my_dict = {
    'k1': 1,
    'k2': 2,
    'k3': 3,
    'k4': 4

}

Hi how to change the key value to K11 , K21 , K31 ..i am receiving run time error when try to change the key names

CodePudding user response:

You can use this:

new_dict = {}

for k, v in my_dict.items():
    new_dict[k   '1'] = v

print(new_dict)

Output: {'k11': 1, 'k21': 2, 'k31': 3, 'k41': 4}

If you want the changes to be applied to my_dict, just add the line my_dict = new_dict

CodePudding user response:

Alternatively you could use a dict comprehension:

new_dict = {k "1": v for (k, v) in my_dict.items()}

CodePudding user response:

To modify a key in a Python dictionary, use Pandas. Import the Pandas library first. Use the DataFrame tool as follows after that.

import pandas as pd
dict_ex = { 'k1' : 1, 'k2' : 2, 'k3' : 3 }
print(dict_ex)
new_dict_ex= { 'K11' : 1, 'K22' : 2, 'K33' : 3 }
df=pd.DataFrame([dict_ex, new_dict_ex])
print(new_dict_ex)
  • Related