Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在字典python中与其他键交换键(不带值)

(其他 - How to swap key with other key in dictionary python (NOT with values))

发布于 2020-12-14 07:17:30

我有一本字典dct = {'one' : 1, 'two' : 2, 'three' : 3 },想像下面那样将“一个”与“两个”交换。

dct = {'two' : 1, 'one' : 2, 'three' : 3}

有什么办法吗?

Questioner
user3685918
Viewed
11
schwobaseggl 2020-12-14 15:19:28

你可以使用python的典型多分配交换模式:

dct["one"], dct["two"] = dct["two"], dct["one"]