Home > Back-end >  Transform generator that returns class with two values into dictionary pythonicly?
Transform generator that returns class with two values into dictionary pythonicly?

Time:03-23

I have a generator that takes a dictionary and generates a class containing the key & value and returns that. I would like to recreate the dictionary from that.

class Limits:
    self._info = {"Test":"Toast"}
    @property
    def absolute(self):
        for (name, value) in self._info['absolute'].items():
            yield AbsoluteLimit(name, value)

class AbsoluteLimit(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

My dirty solution would be:

limits_dict = {}
for elem in Limits.absolute:
    limits_dict[elem.name]=elem.value

Is there a more pythonic way to create the dictionary?

The method in question is from https://github.com/openstack/python-novaclient/blob/master/novaclient/v2/limits.py

CodePudding user response:

Use a dictionary comprehension:

limits_dict = {elem.name: elem.value for elem in Limits.absolute}
  • Related