简体   繁体   English

交换python中的dicts列表中的键

[英]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. 我想重新排序字典,并基本上将键移动一个位置,以便dict将包含具有其后继的发布日期的版本。 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'}

Try using the below code (this only works for python version >= 3.6): 尝试使用以下代码(这仅适用于python版本> = 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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM