简体   繁体   中英

Adding an entry to each dictionary created in a list comprehension

I'm using Python 2.6.6, and I want to do this:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in someList ]  

ie I have a method that returns a dictionary of object attributes, which I'm calling in a list comprehension that builds a list of these dictionaries, and I want to add one additional property to each of them. But the above syntax leaves me with a list of NoneType's, as does this:

result = [ otherMethod.getDict(x) + {'foo': x.bar} for x in someList ]  

Sure I could use a loop after the list comprehension to append the additional entry - but this is python and I want to do it in one line. Can I?

The problem with:

result = [ otherMethod.getDict(x).update({'foo': x.bar}) for x in list ]  

is that the .update() method of dict returns None as it is a mutilator. Consider this:

result = [ (d.update({'foo': x.bar}), d)[1] for d, x in ((otherMethod.getDict(x), x) for x in list) ]

If we aren't permitted to use a local function like:

def update(d, e)
    d.update(e)
    return d

result = [ update(otherMethod.getDict(x), {'foo': x.bar}) for x in list ]

If instead you don't want the returned dict to be mutated consider:

result = [ dict(otherMethod.getDict(x).values() + ({'foo': x.bar}).values()) for x in list ]  

Which creates a new dict from the concatenation of the values of the old ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM