0

Using Python3, If I have a class named COLOR

class COLOR:
    RED =   '\x1b[41m'
    GREEN = '\x1b[42m'
    BLUE =  '\x1b[44m'

I can create a dictionary as such

myColor = {
    "RED":   COLOR.RED,
    "GREEN": COLOR.GREEN,
    "BLUE":  COLOR.BLUE,
}

Is there a pythonic way to programmatically loop through all elements in the class and automatically create the dictionary?

shepster
  • 339
  • 3
  • 13
  • 3
    What's the point of this? Instead of `myColor["RED"]` you can use `COLOR.getattr("RED")` – Barmar Jul 15 '21 at 16:25
  • 3
    You might also want to look into the [`enum`](https://docs.python.org/3/library/enum.html) class. – Barmar Jul 15 '21 at 16:26

1 Answers1

0

Try the built-in function dir():

>>> dir(COLOR)
['BLUE', 'GREEN', 'RED', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

Use a dictionary comprehension:

mydict = {name: getattr(COLOR, name)
    for name in dir(COLOR)
    if not name.startswith("__")}

Check the result:

>>> mydict
{'BLUE': '\x1b[44m', 'GREEN': '\x1b[42m', 'RED': '\x1b[41m'}
Nayuki
  • 17,911
  • 6
  • 53
  • 80