Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform generator that returns class with two values into dictionary pythonicly?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Use a dictionary comprehension:

limits_dict = {elem.name: elem.value for elem in Limits.absolute}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading