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