Python 如何通过值来唯一dict?
我想在dict中复制唯一的值。它如下所示:Python 如何通过值来唯一dict?,python,dictionary,duplicates,unique,Python,Dictionary,Duplicates,Unique,我想在dict中复制唯一的值。它如下所示: d = { "a":1, "b":2, "c":2, "d":3, "e":4, "f":5, "g":1, "h":2, "i":2, "j":1, "k":1} 以下是我所做的: # sort and unique the dict values obj = d.values() K = [] K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0] V=[] f
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
以下是我所做的:
# sort and unique the dict values
obj = d.values()
K = []
K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0]
V=[]
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
d_out = dict(zip(K, V))
一,。
那么,K,V的顺序正确吗?
此外,它可能有点复杂,有人能给出一个简单的解决方案,以独特的dict的价值观
二,。
下面能更简单一些吗
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
这不适用于我的测试:
[V.append([k for k, v in obj.iteritems() if v == v1][0]) for v1 in L]
三,。
我意识到我可以使用交换键值来实现这一点(通过其值使dict唯一),但我不知道在交换导致键与此冲突时如何选择键:
dict((value, key) for key, value in my_dict.iteritems())
我知道如果再次交换它该值将是唯一的,但是,当发生密钥冲突时,这只会覆盖密钥,没有机会进行选择。我感到困惑,为什么这没有给出关键冲突错误?我能做些什么来选择丑陋的方式旁边的键吗?稍后覆盖新的dict的键
四,。
我搜索并找到了一些关于python-dict的“无”值,这些值都得到了很好的讨论,任何人都可以给我一个示例,说明它的用途以及在使用python-dict时会受到什么影响
try it out:
from collections import defaultdict
dout = defaultdict(dict)
for k,v in d.iteritems():
dout[v] = k
dout = dict(dout)
fdict = dict(zip(dout.values(), dout.keys()))
注意:字典没有重复键,所以输入字典没有重复键
希望它能起作用
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
# Extract the dictionary into a list of (key, value) tuples.
t = [(k, d[k]) for k in d]
# Sort the list -- by default it will sort by the key since it is
# first in the tuple.
t.sort()
# Reset the dictionary so it is ready to hold the new dataset.
d = {}
# Load key-values into the dictionary. Only the first value will be
# stored.
for k, v in t:
if v in d.values():
continue
d[k] = v
print d
也许这会有所帮助:
import collections
d = ... # like above
d1 = collections.defaultdict(list)
for k, v in d.iteritems():
d1[v].append(k)
print d1
谢谢,交换2次确实不能解决我的问题,正如我在我的问题上所说的,但是假设值将被复制,那么如何在新生成的dict中选择keyvalue对?我可以把控制点放在哪里?谢谢jathanism,我想你的意思是我应该在某人的答案上打勾,而不是添加有用的值。