反转/反转字典映射
给定一本这样的字典:
my_map = {'a': 1, 'b': 2}
如何反转该映射以获得:
inv_map = {1: 'a', 2: 'b'}
Given a dictionary like so:
my_map = {'a': 1, 'b': 2}
How can one invert this map to get:
inv_map = {1: 'a', 2: 'b'}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
字典值是集合的情况。 像:
逆像:
输出是这样的:
A case where the dictionary values is a set. Like:
The inverse would like:
The output is like this:
有很多答案,但没有找到任何明确的答案,以防我们谈论具有非唯一值的字典。
解决方案是:
示例:
如果初始字典
my_map = {'c': 1, 'd': 5, 'a': 5, 'b': 10}
那么,运行上面的代码会给:
Lot of answers but didn't find anything clean in case we are talking about a dictionary with non-unique values.
A solution would be:
Example:
If initial dict
my_map = {'c': 1, 'd': 5, 'a': 5, 'b': 10}
then, running the code above will give:
列表和字典理解的结合。 可以处理重复的键
Combination of list and dictionary comprehension. Can handle duplicate keys
我发现这个版本比接受的 10000 个键的字典版本快 10% 以上。
I found that this version is more than 10% faster than the accepted version of a dictionary with 10000 keys.
除了上面建议的其他函数之外,如果您喜欢 lambda:
或者,您也可以这样做:
In addition to the other functions suggested above, if you like lambdas:
Or, you could do it this way too:
我认为最好的方法是定义一个类。 这是“对称字典”的实现:
如果需要,删除和迭代方法很容易实现。
这种实现比反转整个字典(这似乎是本页上最流行的解决方案)更有效。 更不用说,您可以根据需要在 SymDict 中添加或删除值,并且您的逆向字典将始终保持有效 - 如果您只是将整个字典逆向一次,则情况并非如此。
I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":
Deletion and iteration methods are easy enough to implement if they're needed.
This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.
如果值不唯一,并且您有点顽固:
特别是对于大型字典,请注意此解决方案的效率远低于答案 Python 反转/反转映射,因为它多次循环
items()
。If the values aren't unique, and you're a little hardcore:
Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over
items()
multiple times.这可以处理非唯一值并保留唯一情况的大部分外观。
对于 Python 3.x,将
itervalues
替换为values
。This handles non-unique values and retains much of the look of the unique case.
For Python 3.x, replace
itervalues
withvalues
.我知道这个问题已经有很多好的答案,但我想分享这个非常简洁的解决方案,它还可以处理重复值:
这依赖于
set.add
始终返回Python 中没有
。I am aware that this question already has many good answers, but I wanted to share this very neat solution that also takes care of duplicate values:
This relies on the fact that
set.add
always returnsNone
in Python.这是另一种方法。
Here is another way to do it.
函数对于列表类型的值是对称的; 执行reverse_dict(reverse_dict(dictionary))时元组被转换为列表
Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))
由于与值不同,字典在字典中需要一个唯一的键,因此我们必须将反转的值附加到一个排序列表中,以包含在新的特定键中。
Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.
非双射映射的快速函数解决方案(值不唯一):
理论上,这应该比像 势在必行的解决方案。
不幸的是,这些值必须是可排序的,groupby 需要排序。
Fast functional solution for non-bijective maps (values not unique):
In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.
Unfortunately the values have to be sortable, the sorting is required by groupby.
在 python 2.7/3.x 上尝试这个
Try this for python 2.7/3.x
这将提供如下输出:{1: ['a', 'd'], 2: ['b'], 3: ['c']}
This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}
当前 python 3.x 版本的 lambda 解决方案:
结果:
此解决方案不检查重复项。
一些备注:
传入当前密钥。 它返回一个元组。
也接受映射的结果,因此我们可以跳过转换为
列表。
for
循环。 它还避免了对于那些数学不好的人使用列表理解
;-)A lambda solution for current python 3.x versions:
Result:
This solution does not check for duplicates.
Some remarks:
pass in the current key. It returns a tuple.
also accepts the result of a map, so we can skip the conversion to a
list.
for
loop. It also avoids using alist comprehension
for those who are bad at math ;-)从 如果 my_map 中的值不唯一:开始,我遇到了一个问题,不仅值不是唯一的,但此外,它们是一个列表,列表中的每个项目又由三个元素组成的列表:字符串值、数字和另一个数字。
示例:
mymap['key1']
为您提供:我只想用键切换字符串值,将两个数字元素保持在同一位置。 您只需要另一个嵌套的 for 循环即可:
示例:
inv_map['abc']
现在为您提供:Taking up the highly voted answer starting If the values in my_map aren't unique:, I had a problem where not only the values were not unique, but in addition, they were a list, with each item in the list consisting again of a list of three elements: a string value, a number, and another number.
Example:
mymap['key1']
gives you:I wanted to switch only the string value with the key, keeping the two number elements at the same place. You simply need another nested for loop then:
Example:
inv_map['abc']
now gives you:即使原始字典中有非唯一值,这也有效。
This works even if you have non-unique values in the original dictionary.
根据用例,可能有一种使用枚举的方法:
您可以双向访问值:
如果开发人员不知道“a”,而是包含在变量中
my_var = 'a',相当于
my_dict[my_var]
是:Depending on the use case, there is possibly a way to use enum:
You can access the values in both direction:
If 'a' is not known by the developper but rather contained in a variable
my_var = 'a'
, the equivalent ofmy_dict[my_var]
would be:我会在 python 2 中这样做。
I would do it that way in python 2.
Python 3+:
Python 2:
Python 3+:
Python 2:
假设字典中的值是唯一的:
Python 3:
Python 2:
Assuming that the values in the dict are unique:
Python 3:
Python 2:
如果
my_map
中的值不唯一:Python 3:
Python 2:
If the values in
my_map
aren't unique:Python 3:
Python 2:
要在保留映射类型的同时执行此操作(假设它是
dict
或dict
子类):To do this while preserving the type of your mapping (assuming that it is a
dict
or adict
subclass):试试这个:(
注意字典视图上的Python文档明确保证
.keys()
和.values()
的元素顺序相同,这使得上述方法能够工作。)或者:
或者使用 python 3.0字典理解
Try this:
(Note that the Python docs on dictionary views explicitly guarantee that
.keys()
and.values()
have their elements in the same order, which allows the approach above to work.)Alternatively:
or using python 3.0's dict comprehensions
另一种更实用的方式:
Another, more functional, way:
我们还可以使用
defaultdict
反转具有重复键的字典:请参阅 此处:
We can also reverse a dictionary with duplicate keys using
defaultdict
:See here:
这扩展了 Robert 的答案,适用于字典中的值不唯一的情况。
该实现受到限制,因为您不能使用
reversed
两次并恢复原始状态。 它本身并不对称。 它是使用 Python 2.6 进行测试的。 这里是我如何打印结果字典的用例。如果您更愿意使用
set
而不是list
,并且可能存在对此有意义的无序应用程序,而不是setdefault(v, []) .append(k)
,使用setdefault(v, set()).add(k)
。This expands upon the answer by Robert, applying to when the values in the dict aren't unique.
The implementation is limited in that you cannot use
reversed
twice and get the original back. It is not symmetric as such. It is tested with Python 2.6. Here is a use case of how I am using to print the resultant dict.If you'd rather use a
set
than alist
, and there could exist unordered applications for which this makes sense, instead ofsetdefault(v, []).append(k)
, usesetdefault(v, set()).add(k)
.例如,您有以下字典:
并且您希望以倒置的形式获得它:
第一个解决方案。 要反转字典中的键值对,请使用
for
循环方法:第二种解决方案。 使用字典理解方法进行反演:
第三种解决方案。 使用恢复反转方法(依赖于第二种解决方案):
For instance, you have the following dictionary:
And you wanna get it in such an inverted form:
First Solution. For inverting key-value pairs in your dictionary use a
for
-loop approach:Second Solution. Use a dictionary comprehension approach for inversion:
Third Solution. Use reverting the inversion approach (relies on the second solution):