[英]Inverting Dictionaries in Python
I want to know which would be an efficient method to invert dictionaries in python. 我想知道哪个是在python中反转字典的有效方法。 I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared.
我还希望通过比较键来消除重复值,并选择较大的值,假设它们可以进行比较。 Here is inverting a dictionary:
这是反转字典:
inverted = dict([[v,k] for k,v in d.items()])
To remove duplicates by using the largest key, sort your dictionary iterator by value. 要使用最大的键删除重复项,请按值对字典迭代器进行排序。 The call to dict will use the last key inserted:
对dict的调用将使用插入的最后一个键:
import operator
inverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1)))
Here is a simple and direct implementation of inverting a dictionary and keeping the larger of any duplicate values: 这是一个简单而直接的实现,它反转字典并保留任何重复值中较大的值:
inverted = {}
for k, v in d.iteritems():
if v in inverted:
inverted[v] = max(inverted[v], k)
else:
inverted[v] = k
This can be tightened-up a bit with dict.get() : 这可以用dict.get()收紧一点:
inverted = {}
for k, v in d.iteritems():
inverted[v] = max(inverted.get(v, k), k)
This code makes fewer comparisons and uses less memory than an approach using sorted() . 与使用sorted()的方法相比,此代码使用更少的比较并使用更少的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.