Add dictionary key/value to list comprehension

54 Views Asked by At

I have the following function that is being used to return results for an API. What I want to do is show self.ced_url within sources as well. What I'm not understanding is how to add that dictionary key/value into the list comprehension.

def to_dict(self):
    ret = {
        "event_data_url": self.ced_url,
        "sources": [s.to_dict() for s in self.sources]
    }
    return ret
1

There are 1 best solutions below

1
On

EDIT: Incorporated Kaya's suggestion to use ret['sources'].append(self.ced_url)

Assuming you want ced_url as part of sources in ret:

def to_dict(self):
    ret = {
        "event_data_url": self.ced_url,
        "sources": [s.to_dict() for s in self.sources]
    }
    ret['sources'].append(self.ced_url)
    return ret