0

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  
max 2p
  • 27
  • 4
  • Does this answer your question? [Change the name of a key in dictionary](https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary) – Michael Szczesny Nov 16 '20 at 14:13

2 Answers2

1

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.

ChaddRobertson
  • 605
  • 3
  • 11
  • 30
  • `dict(zip(keys,vals))` – rioV8 Nov 16 '20 at 14:25
  • ```zip()``` is wonderful and I agree completely - sometimes its easier to see where everything is going though. This is why I linked the other article. – ChaddRobertson Nov 16 '20 at 14:27
  • don't teach people the elaborate way if there is a very clean simple way – rioV8 Nov 16 '20 at 14:29
  • I answered in a way that helped me learn dictionaries when I found many other things confusing. I am not claiming that the above is the most effective way at all (hence my link). Have added ```zip()``` to the answer. – ChaddRobertson Nov 16 '20 at 14:35
0

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

jaswanth
  • 515
  • 2
  • 7