如何交换字典中的键和值?
我收到一个字典作为输入,并希望返回一个字典,其键将是输入的值,其值将是相应的输入键。 价值观是独一无二的。
例如,假设我的输入是:
a = dict()
a['one']=1
a['two']=2
我希望我的输出是:
{1: 'one', 2: 'two'}
为了澄清,我希望我的结果相当于以下内容:
res = dict()
res[1] = 'one'
res[2] = 'two'
有什么简洁的 Pythonic 方法可以实现这一点吗?
I receive a dictionary as input, and would like to to return a dictionary whose keys will be the input's values and whose value will be the corresponding input keys. Values are unique.
For example, say my input is:
a = dict()
a['one']=1
a['two']=2
I would like my output to be:
{1: 'one', 2: 'two'}
To clarify I would like my result to be the equivalent of the following:
res = dict()
res[1] = 'one'
res[2] = 'two'
Any neat Pythonic way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
Python 2:
Python 3(感谢@erik):
Python 2:
Python 3 (thanks to @erik):
从 Python 2.7 开始,包括 3.0+,有一个可以说更短、更易读的版本:
From Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version:
您可以使用 字典理解:
Python 3
Python 2
编辑:对于 Python 3、使用
a.items()
代替a.iteritems()
。 关于它们之间差异的讨论可以在 iteritems in Python on SO 中找到。You can make use of dict comprehensions:
Python 3
Python 2
Edited: For Python 3, use
a.items()
instead ofa.iteritems()
. Discussions about the differences between them can be found in iteritems in Python on SO.Python 3
Python 2
Python 3
Python 2
当前的主要答案假设值是唯一的,但情况并非总是如此。 如果值不唯一怎么办? 你会丢失信息!
例如:
返回
{2: 'b', 3: 'a'}
。关于
'c'
的信息被完全忽略。理想情况下,它应该类似于
{2: ['b','c'], 3: ['a']}
。 这就是底层实现的作用。Python 2.x
Python 3.x
The current leading answer assumes values are unique which is not always the case. What if values are not unique? You will loose information!
For example:
returns
{2: 'b', 3: 'a'}
.The information about
'c'
was completely ignored.Ideally it should had be something like
{2: ['b','c'], 3: ['a']}
. This is what the bottom implementation does.Python 2.x
Python 3.x
res = dict(zip(a.values(), a.keys()))
res = dict(zip(a.values(), a.keys()))
您可以尝试:
Python 3
Python 2
则无法“反转”字典
{'one':1,'two':1}
。 新字典只能包含一项带有键1
的项目。{'one':[1]}
。[1]
是有效值,但不是有效键。请参阅 python 邮件列表上的此线程关于该主题的讨论。
You could try:
Python 3
Python 2
Beware that you cannot 'reverse' a dictionary if
{'one':1,'two':1}
. The new dictionary can only have one item with key1
.{'one':[1]}
.[1]
is a valid value but not a valid key.See this thread on the python mailing list for a discussion on the subject.
扩展 Ilya Prokin 的响应的另一种方法是实际使用
reversed
函数。本质上,您的字典是通过(使用
.items()
)进行迭代的,其中每个项目都是一个键/值对,并且这些项目与reversed
函数进行交换。 当它传递给 dict 构造函数时,它会将它们转换为您想要的值/键对。Another way to expand on Ilya Prokin's response is to actually use the
reversed
function.In essence, your dictionary is iterated through (using
.items()
) where each item is a key/value pair, and those items are swapped with thereversed
function. When this is passed to thedict
constructor, it turns them into value/key pairs which is what you want.甚至更好,但仅适用于 Python 3:
or even better, but only works in Python 3:
对哈维尔答案的改进建议:
您可以只编写
d
而不是d.keys()
,因为如果您使用迭代器遍历字典,它将返回键的相关词典。前任。 对于这种行为:
Suggestion for an improvement for Javier answer :
Instead of
d.keys()
you can write justd
, because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.Ex. for this behavior :
可以通过字典理解轻松完成:
Can be done easily with dictionary comprehension:
.items()
返回(key, value)
元组列表。map()
遍历列表的元素,并将lambda x:[::-1]
应用于每个元素(元组)以反转它,因此每个元组都变为 <从地图中吐出的新列表中的 code>(value, key) 。 最后,dict()
从新列表中创建一个字典。.items()
returns a list of tuples of(key, value)
.map()
goes through elements of the list and applieslambda x:[::-1]
to each its element (tuple) to reverse it, so each tuple becomes(value, key)
in the new list spitted out of map. Finally,dict()
makes a dict from the new list.哈南的答案是正确的,因为它涵盖了更一般的情况(其他答案对于不知道重复情况的人来说有点误导)。 Hanan 的答案的改进是使用 setdefault:
Hanan's answer is the correct one as it covers more general case (the other answers are kind of misleading for someone unaware of the duplicate situation). An improvement to Hanan's answer is using setdefault:
使用循环:-
Using loop:-
如果您使用的是 Python3,则略有不同:
If you're using Python3, it's slightly different:
添加就地解决方案:
在 Python3 中,使用
list(d.keys())
至关重要,因为dict.keys
返回一个视图 键。 如果您使用的是 Python2,d.keys()
就足够了。Adding an in-place solution:
In Python3, it is critical that you use
list(d.keys())
becausedict.keys
returns a view of the keys. If you are using Python2,d.keys()
is enough.我发现这个版本是最全面的版本:
a = {1: 'one', 2: 'two'}
swapped_a = {value : key for key, value in a.items()}
print(swapped_a)
输出:
{'一':1,'二':2}
I find this version the most comprehensive one:
a = {1: 'one', 2: 'two'}
swapped_a = {value : key for key, value in a.items()}
print(swapped_a)
output :
{'one': 1, 'two': 2}
在我看来,另一种方法的可读性不如其他一些答案:
new_dict = dict(zip(*list(zip(*old_dict.items()))[::-1]))
其中
list(zip(*old_dict.items()))[::-1]
给出 2 个元组的列表,即old_dict
的值和键, 分别。An alternative that is not quite as readable (in my opinion) as some of the other answers:
new_dict = dict(zip(*list(zip(*old_dict.items()))[::-1]))
where
list(zip(*old_dict.items()))[::-1]
gives a list of 2 tuples,old_dict
's values and keys, respectively.