Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap keys in list of dicts in python

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'}
like image 946
likas666 Avatar asked Aug 14 '19 11:08

likas666


People also ask

Can Dicts have same keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can we replace Key in dictionary 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.


1 Answers

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'}
like image 80
U12-Forward Avatar answered Nov 21 '22 01:11

U12-Forward