簡體   English   中英

返回字典中常用值的鍵的字典

[英]Return a dictionary of keys of common values in a dictionary

我想返回另一個字典中出現多次的元素鍵的字典。

例子:

x = {1:10, 2:12, 3:14, 4:10, 5:14} 

答案會回來

{10:[1,4], 14:[3,5]} 

這個怎么樣

# 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

這是想到的最簡單的解決方案

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()以某種方式..

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM