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