-3

I got an python interview question: #Dictionary Convert

i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}

in to

output = {"car":["volvo", "benz"], "bike":["yamaha", "hero"]}
DYZ
  • 55,249
  • 10
  • 64
  • 93

1 Answers1

0

You can use the try/except process to reorder the dictionary.

i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}

output ={}
for k, it in i.items():
    try:
        output[it].append(k)
    except KeyError:
        output[it] = [k]
    
 print(output)

Output:

{'car': ['volvo', 'benz'], 'bike': ['yamaha', 'hero']}
LevB
  • 925
  • 6
  • 10
  • Thanks for the answer, It worked. Can you please elaborate more step by step what was going on? what is it here? – Peter Nanii Mar 09 '21 at 18:43
  • 1. You iterate through the dictionary using .items(), which gives you both the key and the value. 2. You try to add the key to your list. 3. If the list doesn't yet exist (KeyError) because it's the first entry, you create it. – LevB Mar 10 '21 at 11:31