Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: search in list of lists of dictionaries

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'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading