Is there any way I can change the keys in a dictionary at once?
For example, mydict={0:0.0, 1:1.1, 2:2.2}
.
How can I get newdict={1:0.0, 2:1.1, 0:2.2}
?
CodePudding user response:
If you want to do it in Python 3 so you can control the order of keys in mydict
, then you could use a pandas Series
to help assign new keys to the dictionary values.
import pandas as pd
mydict={0:0.0, 1:1.1, 2:2.2}
new_keys = [1, 2, 0]
# Make dictionary with same values assigned to new keys.
newdict = pd.Series(list(mydict.values()),
index=new_keys) \
.to_dict()
newdict
# {1: 0.0, 2: 1.1, 0: 2.2}