简体   繁体   中英

Return a dictionary of keys of common values in a dictionary

I want to return a dictionary of the keys of the elements in another dictionary which occur more than once.

Example:

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

The answer will return

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

How about this

# 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

This is the simplest solution that comes to mind

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]}

I wonder if itertools.groupby() can be used here somehow..

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM