Python Forum
Move a key:value in a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Move a key:value in a dictionary
#1
I created the following dictionary and added another key:value.

>>> super_hero_names = {
...     'Superman' : 'Clark Kent',
...     'Spiderman' : 'Peter Parker'
... }
>>>
>>> batman = {'Batman' : 'Bruce'}
>>> super_hero_names.update(batman)
>>> super_hero_names
{'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker', 'Batman': 'Bruce'}
>>> super_hero_names.update(Batman = "Bruce Wayne")
>>> super_hero_names
{'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker', 'Batman': 'Bruce Wayne'}
How do I move 'Batman': 'Bruce Wayne' as the first in the dictionary so the outcome would make the last key:value the first?

Is there a way to "add" the element where I want? Second, can the last key:value be moved?

Here is the desired outcome:

>>> super_hero_names
{'Batman': 'Bruce Wayne','Superman': 'Clark Kent', 'Spiderman': 'Peter Parker'}
Best,
Dave
Reply


Messages In This Thread
Move a key:value in a dictionary - by dgrunwal - Feb-23-2021, 09:17 PM
RE: Move a key:value in a dictionary - by buran - Feb-23-2021, 09:26 PM
RE: Move a key:value in a dictionary - by snippsat - Feb-23-2021, 10:18 PM
RE: Move a key:value in a dictionary - by dgrunwal - Feb-24-2021, 02:43 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020