0

If I have a dictionary like the one below:

myd = {"Dave": 19, 
       "Amy": 16, 
       "Jack": 21, 
       "Jose": 22, 
       "Ximena": 21, 
       "Seta": 26 } 

is it possible to write a python command to replace “Amy” with “Mike”, keeping the value?

awesoon
  • 32,469
  • 11
  • 74
  • 99
Julio
  • 2,573
  • 2
  • 11
  • 7

2 Answers2

3

The easiest way is to do something like this:

  myd["Amber"] = myd.pop("Dave")

This creates a new key of "Amber" and gives it the value of "Dave", while also removing "Dave" from the dictionary.

EDIT: I missed that figs had posted a link to answer as a comment already. After checking that link, I realized I never even thought about the possibility of an ordered dictionary. So, if that's what you need, check out figs link as there is a nice solution in there. My given solution will only work for a normal dictionary.

user2566987
  • 308
  • 1
  • 9
1

you can use update and pop:

demo:

>>> myd = {"Dave":19, "Amy":16, "Jack":21, "Jose":22, "Ximena":21, "Seta":26 } 
>>> myd.update([('Mike',myd.pop('Amy'))])
>>> myd
{'Jose': 22, 'Mike': 16, 'Seta': 26, 'Ximena': 21, 'Dave': 19, 'Jack': 21}

pop will remove the key and return its value . update will update the dictionary with key and value

Hackaholic
  • 19,069
  • 5
  • 54
  • 72