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
#2
dict is a mapping. order is not important - originally up to 3.6 dict was unordered collection. Starting 3.6 (as implementation detail) order of insertion is preserved. That is guaranteed from 3.7 onward. So, to get the desired output you need to create a new dictionary. But again, the order is not important in probably 99.99% of the cases when it come to dict.
nilamo likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
@buran is correct but if it's important to you, you will need to implement another dictionary to get what you want. Try this:

batman = temp = {'Batman' : 'Bruce'}
temp.update (super_hero_names)
super_hero_names = temp
nilamo likes this post
Reply
#4
Python 3.9,as merge together with batman dict first it will keep order,not that it matter to much as mention.
>>> d = batman | super_hero_names
>>> d
{'Batman': 'Bruce', 'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker'}
>>> d.update(Batman = "Bruce Wayne")
>>> d
{'Batman': 'Bruce Wayne', 'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker'}
For Python 3.8 d = {**batman, **super_hero_names}.
nilamo likes this post
Reply
#5
Thank you all. Worked like a charm.

In appreciation,
David
Reply


Forum Jump:

User Panel Messages

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