我想返回一个不止一次出现的另一个字典中元素键的字典。
示例:
x = {1:10, 2:12, 3:14, 4:10, 5:14}
答案将返回
{10:[1,4], 14:[3,5]}
答案 0 :(得分:0)
这个怎么样
# python 2.x
x = {1:10, 2:12, 3:14, 4:10, 5:14}
a = {}
for key, value in x.iteritems(): # x.items() if python 3.x
a.setdefault(key, []).append(value)
for key, value in x.iteritems():
if len(value) <= 1
a.pop(key, None)
print a
答案 1 :(得分:0)
这是我想到的最简单的解决方案
x = {1: 10, 2: 12, 3: 14, 4: 10, 5: 14}
res = {}
for k, v in x.items():
temp = res.setdefault(v, [])
temp.append(k)
res = {k: v for k, v in res.items() if len(v)>1}
print(res) # {10: [1, 4], 14: [3, 5]}
我想知道itertools.groupby()
是否可以在某处使用..
答案 2 :(得分:0)
x = {1:10, 2:12, 3:14, 4:10, 5:14}
res = {}
for k, v in x.iteritems():
res[v] = res.get(v, [])
res[v].append(k)
{k: v for k, v in res.items() if len(v) > 1}