max 2p
max 2p

Reputation: 27

How to replace existing key in a dictionary in python?

So , I have this code.
I want to replace the specific existing key at index 1 in a dictionary in python. Anyone have an idea on this?

from collections import OrderedDict
regDict= OrderedDict()
regDict[("glenn")] = 1
regDict[("elena")] = 2
print("dict",regDict)

prints:

dict OrderedDict([('glenn', 1), ('elena', 2)])

target output:

dict OrderedDict([('glenn', 1), ('new', 2)])  # replacing key in index 1  

Upvotes: 0

Views: 1360

Answers (2)

ChaddRobertson
ChaddRobertson

Reputation: 653

Your approach towards making a dictionary is a little bit off. Let's start by making a new dictionary from two lists (one for keys and one for values):

keys = ['a', 'b', 'c']
vals = [1.0, 2.0, 3.0]

dictionary = {keys[i]:value for i, value in enumerate(vals)}

This gives us the following:

{'a': 1.0, 'b': 2.0, 'c': 3.0}

You can also go here for some more help with making dictionaries: Convert two lists into a dictionary

To replace the 'a' key with 'aa', we can do this:

new_key = 'aa'
old_key = 'a'

dictionary[new_key] = dictionary.pop(old_key)

Giving us:

{'b': 2.0, 'c': 3.0, 'aa': 1.0}

Other ways to make a dictionary:

dictionary = {k: v for k, v in zip(keys, values)}

dictionary = dict(zip(keys, values))

Where 'keys' and 'values' are both lists.

Upvotes: 1

jaswanth
jaswanth

Reputation: 525

This is a very bad approach for a dictionary but a solution would look like below

index = len(regDict)-1
key = list(regDict.keys())[index]
value = regDict[key]
regDict["new"] = value

Note: This will only work if you want to change the last inserted key

Upvotes: 0

Related Questions