I want to swap keys in a dictionary but keep the values the same.
This script will be used to set end of service dates. In essence the release date of the newer version is the end of service date of the older one. I have an ordered dictionary containing the version as a key and the release date as its value. Looking roughly like this:
{'10.1.0: '2019-01-01',
'9.3.0': '2018-11-02',
'9.2.0': '2018-06-20',
'9.1.0': '2018-03-06'}
i want to re-sort the dictionary and basically move the keys up one spot so that the dict will contain the version with the release date of its successor. The latest version can either contain no value or be deleted. My ideal outcome would look like this:
{'9.3.0': '2019-01-01',
'9.2.0': '2018-11-02',
'9.1.0': '2018-06-20'}
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.
Try using the below code (this only works for python version >= 3.6):
>>> d = {'10.1.0: ':'2019-01-01',
'9.3.0': '2018-11-02',
'9.2.0': '2018-06-20',
'9.1.0': '2018-03-06'}
>>> dict(zip(list(d)[1:], d.values()))
{'9.3.0': '2019-01-01', '9.2.0': '2018-11-02', '9.1.0': '2018-06-20'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With