-1

How do you print a dictionary in Python where if the value matches another value in the dictionary, they are printed on the same line?

Code:

result = {'light':4,'plane':4, 'vehicle':5}

print(result)

Current Output:

{'light': 4, 'plane': 4, 'vehicle': 5}

Expected Output:

4 light, plane
5 vehicle

How would you also count the frequency of the words as in the expected output? For example, light + plane is 2.

maciejwww
  • 758
  • 10
  • 22
Dave
  • 766
  • 8
  • 23
  • f.e. this answer https://stackoverflow.com/a/485368/7505395 from the dupe (there are some handling grouping for multiple values) – Patrick Artner May 23 '18 at 05:29

1 Answers1

1

You can try like this :

from collections import defaultdict

v = defaultdict(list)
d = {'light':4,'plane':4, 'vehicle':5}

for key, value in sorted(d.items()):
    v[value].append(key)

This will also work :

k = {}

for key, value in sorted(d.items()):
    k.setdefault(value, []).append(key)

UPDATE : If you want to print it in your desired format :

for i, j in v.items():
    print(i,", ".join(l for l in j))

O/P will be like :

4 light, plane
5 vehicle

UPDATE 2: The code to print in the desired format mentioned above is completed below:

from collections import defaultdict
v = defaultdict(list)
d = {'light':4,'plane':4, 'vehicle':5}
for key, value in sorted(d.items()):
    v[value].append(key)
for i, j in v.items():
    print(i,", ".join(l for l in j))
Dave
  • 766
  • 8
  • 23
Vikas Periyadath
  • 2,930
  • 1
  • 17
  • 28