如何交换字典中的键和值?

发布于 2024-07-26 17:13:23 字数 342 浏览 4 评论 0原文

我收到一个字典作为输入,并希望返回一个字典,其键将是输入的值,其值将是相应的输入键。 价值观是独一无二的。

例如,假设我的输入是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

天涯离梦残月幽梦 2024-08-02 17:13:23

Python 2:

res = dict((v,k) for k,v in a.iteritems())

Python 3(感谢@erik):

res = dict((v,k) for k,v in a.items())

Python 2:

res = dict((v,k) for k,v in a.iteritems())

Python 3 (thanks to @erik):

res = dict((v,k) for k,v in a.items())
怪我鬧 2024-08-02 17:13:23
new_dict = dict(zip(my_dict.values(), my_dict.keys()))
new_dict = dict(zip(my_dict.values(), my_dict.keys()))
好菇凉咱不稀罕他 2024-08-02 17:13:23

从 Python 2.7 开始,包括 3.0+,有一个可以说更短、更易读的版本:

>>> my_dict = {'x':1, 'y':2, 'z':3}
>>> {v: k for k, v in my_dict.items()}
{1: 'x', 2: 'y', 3: 'z'}

From Python 2.7 on, including 3.0+, there's an arguably shorter, more readable version:

>>> my_dict = {'x':1, 'y':2, 'z':3}
>>> {v: k for k, v in my_dict.items()}
{1: 'x', 2: 'y', 3: 'z'}
晌融 2024-08-02 17:13:23

您可以使用 字典理解

Python 3

res = {v: k for k, v in a.items()}

Python 2

res = {v: k for k, v in a.iteritems()}

编辑:对于 Python 3、使用a.items()代替a.iteritems()。 关于它们之间差异的讨论可以在 iteritems in Python on SO 中找到。

You can make use of dict comprehensions:

Python 3

res = {v: k for k, v in a.items()}

Python 2

res = {v: k for k, v in a.iteritems()}

Edited: For Python 3, use a.items() instead of a.iteritems(). Discussions about the differences between them can be found in iteritems in Python on SO.

一页 2024-08-02 17:13:23
In [1]: my_dict = {'x':1, 'y':2, 'z':3}

Python 3

In [2]: dict((value, key) for key, value in my_dict.items())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}

Python 2

In [2]: dict((value, key) for key, value in my_dict.iteritems())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}
In [1]: my_dict = {'x':1, 'y':2, 'z':3}

Python 3

In [2]: dict((value, key) for key, value in my_dict.items())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}

Python 2

In [2]: dict((value, key) for key, value in my_dict.iteritems())
Out[2]: {1: 'x', 2: 'y', 3: 'z'}
一江春梦 2024-08-02 17:13:23

当前的主要答案假设值是唯一的,但情况并非总是如此。 如果值不唯一怎么办? 你会丢失信息!
例如:

d = {'a':3, 'b': 2, 'c': 2} 
{v:k for k,v in d.iteritems()} 

返回{2: 'b', 3: 'a'}

关于'c'的信息被完全忽略。
理想情况下,它应该类似于 {2: ['b','c'], 3: ['a']}。 这就是底层实现的作用。

Python 2.x

def reverse_non_unique_mapping(d):
    dinv = {}
    for k, v in d.iteritems():
        if v in dinv:
            dinv[v].append(k)
        else:
            dinv[v] = [k]
    return dinv

Python 3.x

def reverse_non_unique_mapping(d):
    dinv = {}
    for k, v in d.items():
        if v in dinv:
            dinv[v].append(k)
        else:
            dinv[v] = [k]
    return dinv

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:

d = {'a':3, 'b': 2, 'c': 2} 
{v:k for k,v in d.iteritems()} 

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

def reverse_non_unique_mapping(d):
    dinv = {}
    for k, v in d.iteritems():
        if v in dinv:
            dinv[v].append(k)
        else:
            dinv[v] = [k]
    return dinv

Python 3.x

def reverse_non_unique_mapping(d):
    dinv = {}
    for k, v in d.items():
        if v in dinv:
            dinv[v].append(k)
        else:
            dinv[v] = [k]
    return dinv
半寸时光 2024-08-02 17:13:23

res = dict(zip(a.values(), a.keys()))

res = dict(zip(a.values(), a.keys()))

轻许诺言 2024-08-02 17:13:23

您可以尝试:

Python 3

d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.items())
d2
  {'two': 2, 'one': 1}

Python 2

d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.iteritems())
d2
  {'two': 2, 'one': 1}

则无法“反转”字典

  1. 请注意,如果多个键共享相同的值, 。 例如{'one':1,'two':1}。 新字典只能包含一项带有键 1 的项目。
  2. 其中一个或多个值是不可散列的。 例如{'one':[1]}[1] 是有效值,但不是有效键。

请参阅 python 邮件列表上的此线程关于该主题的讨论。

You could try:

Python 3

d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.items())
d2
  {'two': 2, 'one': 1}

Python 2

d={'one':1,'two':2}
d2=dict((value,key) for key,value in d.iteritems())
d2
  {'two': 2, 'one': 1}

Beware that you cannot 'reverse' a dictionary if

  1. More than one key shares the same value. For example {'one':1,'two':1}. The new dictionary can only have one item with key 1.
  2. One or more of the values is unhashable. For example {'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.

明月松间行 2024-08-02 17:13:23

扩展 Ilya Prokin 的响应的另一种方法是实际使用 reversed 函数。

dict(map(reversed, my_dict.items()))

本质上,您的字典是通过(使用 .items())进行迭代的,其中每个项目都是一个键/值对,并且这些项目与 reversed 函数进行交换。 当它传递给 dict 构造函数时,它会将它们转换为您想要的值/键对。

Another way to expand on Ilya Prokin's response is to actually use the reversed function.

dict(map(reversed, my_dict.items()))

In essence, your dictionary is iterated through (using .items()) where each item is a key/value pair, and those items are swapped with the reversed function. When this is passed to the dict constructor, it turns them into value/key pairs which is what you want.

予囚 2024-08-02 17:13:23
new_dict = dict( (my_dict[k], k) for k in my_dict)

甚至更好,但仅适用于 Python 3:

new_dict = { my_dict[k]: k for k in my_dict}
new_dict = dict( (my_dict[k], k) for k in my_dict)

or even better, but only works in Python 3:

new_dict = { my_dict[k]: k for k in my_dict}
牵强ㄟ 2024-08-02 17:13:23

对哈维尔答案的改进建议:

dict(zip(d.values(),d))

您可以只编写 d 而不是 d.keys() ,因为如果您使用迭代器遍历字典,它将返回键的相关词典。

前任。 对于这种行为:

d = {'a':1,'b':2}
for k in d:
 k
'a'
'b'

Suggestion for an improvement for Javier answer :

dict(zip(d.values(),d))

Instead of d.keys() you can write just d, because if you go through dictionary with an iterator, it will return the keys of the relevant dictionary.

Ex. for this behavior :

d = {'a':1,'b':2}
for k in d:
 k
'a'
'b'
有木有妳兜一样 2024-08-02 17:13:23

可以通过字典理解轻松完成:

{d[i]:i for i in d}

Can be done easily with dictionary comprehension:

{d[i]:i for i in d}
執念 2024-08-02 17:13:23
dict(map(lambda x: x[::-1], YourDict.items()))

.items() 返回(key, value) 元组列表。 map() 遍历列表的元素,并将 lambda x:[::-1] 应用于每个元素(元组)以反转它,因此每个元组都变为 <从地图中吐出的新列表中的 code>(value, key) 。 最后,dict() 从新列表中创建一个字典。

dict(map(lambda x: x[::-1], YourDict.items()))

.items() returns a list of tuples of (key, value). map() goes through elements of the list and applies lambda 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.

拿命拼未来 2024-08-02 17:13:23

哈南的答案是正确的,因为它涵盖了更一般的情况(其他答案对于不知道重复情况的人来说有点误导)。 Hanan 的答案的改进是使用 setdefault:

mydict = {1:a, 2:a, 3:b}   
result = {}
for i in mydict:  
   result.setdefault(mydict[i],[]).append(i)
print(result)
>>> result = {a:[1,2], b:[3]}

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:

mydict = {1:a, 2:a, 3:b}   
result = {}
for i in mydict:  
   result.setdefault(mydict[i],[]).append(i)
print(result)
>>> result = {a:[1,2], b:[3]}
不离久伴 2024-08-02 17:13:23

使用循环:-

newdict = {} #Will contain reversed key:value pairs.

for key, value in zip(my_dict.keys(), my_dict.values()):
    # Operations on key/value can also be performed.
    newdict[value] = key

Using loop:-

newdict = {} #Will contain reversed key:value pairs.

for key, value in zip(my_dict.keys(), my_dict.values()):
    # Operations on key/value can also be performed.
    newdict[value] = key
檐上三寸雪 2024-08-02 17:13:23

如果您使用的是 Python3,则略有不同:

res = dict((v,k) for k,v in a.items())

If you're using Python3, it's slightly different:

res = dict((v,k) for k,v in a.items())
隱形的亼 2024-08-02 17:13:23

添加就地解决方案:

>>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> for k in list(d.keys()):
...     d[d.pop(k)] = k
... 
>>> d
{'two': 2, 'one': 1, 'four': 4, 'three': 3}

在 Python3 中,使用 list(d.keys()) 至关重要,因为 dict.keys 返回一个视图 键。 如果您使用的是 Python2,d.keys() 就足够了。

Adding an in-place solution:

>>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> for k in list(d.keys()):
...     d[d.pop(k)] = k
... 
>>> d
{'two': 2, 'one': 1, 'four': 4, 'three': 3}

In Python3, it is critical that you use list(d.keys()) because dict.keys returns a view of the keys. If you are using Python2, d.keys() is enough.

维持三分热 2024-08-02 17:13:23

我发现这个版本是最全面的版本:

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}

随梦而飞# 2024-08-02 17:13:23

在我看来,另一种方法的可读性不如其他一些答案:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文