-2

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]} 
SiHa
  • 7,830
  • 13
  • 34
  • 43
  • 1
    These are values, not elements. Also show us what you've tried already. – DeepSpace Feb 08 '17 at 10:44
  • Possible duplicate of [Python reverse / invert a mapping](http://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping) – Pbd Feb 08 '17 at 10:50

3 Answers3

0

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
kawadhiya21
  • 2,458
  • 21
  • 34
0

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..

Ma0
  • 15,057
  • 4
  • 35
  • 65
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}
khelili miliana
  • 3,730
  • 2
  • 15
  • 28
  • 1
    Although this code might solve the problem, a good answer should always contain an explanation. – BDL Feb 08 '17 at 13:48