Home > other >  python: search in list of lists of dictionaries
python: search in list of lists of dictionaries

Time:11-11

I want to iterate over a list of lists of dictionaries:

data = [
    {'name': 'sravan'},
    {'name': 'bobby'},
    {'name': 'ojsawi', 'number': '123'},
    {'name': 'rohith', 'number': '456'},
    {'name': 'gnanesh', 'number': '123'}
]

Furthermore I want to check each entry if there is a key number where the value is 123. If so, I want to append the value of name of this entry in a new list which would be 'ojsawi' and 'gnanesh' in the above case. Else, I want to append 0 in the new list.

This means, the final new_list with the appended values should look like this: new_list = {0, 0, 'ojsawi', 0, 'gnanesh'}

I have tried different versions/possibillities with 2D for loops and lambdas etc. but I think the main problem is that the lists have different sizes. Any help/tipps would be much appreciated.

CodePudding user response:

You can define it with list comprehensions with a nested if/else in it:

new_list = [x.get('name') if x.get('number') == '123' else 0 for x in data]

Outputting:

[0, 0, 'ojsawi', 0, 'gnanesh']

CodePudding user response:

Other than list comprehensions, you can also do it using map() and functional programming if you want. Note that map() returns an iterator which generates things as you go if you are using a for loop, so if you want the entire result immediately, use list() around your map() function.

def zerofilter(my_dict):
    number = my_dict.get("number")
    if number != "123":
        return 0
    else:
        return my_dict.get("name")

data = [
    {'name': 'sravan'},
    {'name': 'bobby'},
    {'name': 'ojsawi', 'number': '123'},
    {'name': 'rohith', 'number': '456'},
    {'name': 'gnanesh', 'number': '123'}
]

print(list(map(zerofilter, data))) # output is [0, 0, 'ojsawi', 0, 'gnanesh']

# You can also do this:
for res in map(zerofilter, data):
    print(res)
  • Related