Home > Enterprise >  How do I convert a list into a dictionary grouped by object name?
How do I convert a list into a dictionary grouped by object name?

Time:04-21

Say I have a list with classes:

[Blue((2, 1)), Blue((4, 2)), Orange((3, 2))]

How would I convert it into a dictionary of this format using Python, while also using no imports:

{'Blue': [Blue((2, 1)), Blue((4, 2))], 'Orange': [Orange((3, 2))]}

CodePudding user response:

Assuming that Blue and Orange are classes, you can find the classname of each object using type() and the __name__ attribute. Then, you can collect instances of each class into lists using a collections.defaultdict:

from collections import defaultdict

result = defaultdict(list)
for item in data:
    result[type(item).__name__].append(item)

print(result)

If you can't use imports, you can use .setdefault() instead:

result = {}
for item in data:
    result.setdefault(type(item).__name__, []).append(item)

print(result)
  • Related