-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
  • 1,067
  • 1
  • 13
  • 26
Dave
  • 766
  • 9
  • 26
  • 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
  • 9
  • 26
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33