简体   繁体   中英

Remove dict element from list of dicts using lambda

New to python here:

I'm trying to create a new list where every dict from initial list has an element removed, it exists:

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: del d["y"] if "y" in d, arraylist)

I know I can do it using for , using del. But I'm looking to learn something new.

Use a list comprehension:

In [26]: [{x:d[x] for x in d if x != 'y'} for d in arraylist]
Out[26]: [{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]

You can use filter like this

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: dict(filter(lambda (k,v): k != "y", d.iteritems())), arraylist)

You can't use del in a lambda function because del is a statement and a lambda 's body can only be a single expression. You can't put a statement inside an expression. You could make it work with an ordinary function:

def delete_y(d):
    if "y" in d:
        del d['y']
    return d

Note that using del like this modifies the dictionary d in place. This means that returning the modified dictionary (and using the return value to build a new list) is sort of redundant. The original data structure the dictionary came from will already have the modified version.

Maybe its not the shortest way, but it is definitely a convenient way to remove items from a list:

arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]

print arraylist

def containsY(d):
    if 'y' in d.keys():
        del d['y']
        return True
    return False

filter(containsY, arraylist)

print arraylist

output:

[{'y': 2, 'x': 1}, {'y': 2, 'x': 3}, {'y': 2, 'x': 5}, {'y': 2, 'x': 33}, {'y': 8, 'x': 1}]
[{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]

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