Here's a sample dictionary.
example = {'a': 10, 'b': 12, 'c': 10, 'd': 12}
I want to print them like below.
12 b, d
10 a, c
Here's a sample dictionary.
example = {'a': 10, 'b': 12, 'c': 10, 'd': 12}
I want to print them like below.
12 b, d
10 a, c
There are two ways you can approach this problem.
Efficient: collections.defaultdict(list)
Construct a new dictionary with keys and values inverted. Importantly, you can have duplicate values, so we use a list to hold these. The Pythonic approach is to use collections.defaultdict
.
For very large dictionaries, this may have a large memory overhead.
example = {'a': 10, 'b': 12, 'c': 10, 'd': 12}
from collections import defaultdict
d = defaultdict(list)
for k, v in example.items():
d[v].append(k)
for k, v in d.items():
print(k, ' '.join(v))
10 a c
12 b d
Manual: loop of list comprehensions
This way is computationally inefficient, but requires less memory overhead:
for value in set(example.values()):
print(value, ' '.join([k for k, v in example.items() if v == value]))
10 a c
12 b d
Does this achieve what you're after?
for i in set(example.values()):
print (i, [list(example.keys())[j] for j in range(len(example)) if list(example.values())[j]==i])