Python Forum

Full Version: Move a key:value in a dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
@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
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}.
Thank you all. Worked like a charm.

In appreciation,
David