Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how do I iterate only if value is a tuple/list and not a string

Tags:

python

I am currently trying to write a python script/small app that is supposed to read events, and then translate them to a different format. I am also making us of this to dabble a bit in object oriented programming but I am far from an an expert.

I am trying to use a dictionary as map to define the mapping between the source fields and the translated fields.

One of the source fields though (priority in the example) is required twice in the output.

class event():
    def __init__(self, description, priority):
        self.description = description
        self.priority = priority

        pass

    _translateMap = {
       'description': 'message',
       'priority' : ('priority', 'severity')
    }

    def translate(self):
       result = {}
       for key, value in self._translateMap.items():
           for field in value:
               result[field] = getattr(self, key)

       return result

if __name__ == '__main__':
    event1 = event('blahblah','3')
    print event1.translate()

this will print: {'a': 'blahblah', 'e': 'blahblah', 'severity': '3', 'g': 'blahblah', 'm': 'blahblah', 'priority': '3', 's': 'blahblah'}

what I would like to have though is: {'message': 'blahblah', 'severity': '3', 'priority': '3'}

I understand that the problem is iterating through every character of 'message', I am not really sure though what is the best way to avoid this while still being able to parse multiple input values?

or is my expectation that they should work similarly is fundamentally wrong? As mentioned I'm not very experienced yet so if you think the approach doesn't make sense let me know!

Thank you in advance,

like image 722
Eav Avatar asked Jun 11 '26 05:06

Eav


1 Answers

There are two ways you could fix this, you can make the 'message' string into a tuple, so your _translateMap would look like this:

_translateMap = {
    'description': ('message',),
    'priority' : ('priority', 'severity')
}

Otherwise, you could check the type with isinstance each time like this:

def translate(self):
    result = {}
    for key, value in self._translateMap.items():
        if isinstance(value,str):
            result[value] = getattr(self, key)
        else:
            for field in value:
                 result[field] = getattr(self, key)

    return result

I hope this helps. :)

like image 105
DeltaMarine101 Avatar answered Jun 13 '26 19:06

DeltaMarine101



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!