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.
>Solution :
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']