简体   繁体   中英

How to remove empty key-value from dictionary comprehension when applying filter

I am new to python and learning how to use a dictionary comprehension. I have a movie cast dictionary that I would like to filter on a specific value using the dictionary comprehension technique. I was able to get it work but for some reason I get empty dictionaries added as well if the condition is not met. Why does it do it? And how can I ensure these are not included?

movie_cast = [{'id': 90633,'name': 'Gal Gadot','cast_id': 0, 'order': 0},
              {'id': 62064, 'name': 'Chris Pine','cast_id': 15, 'order': 1},
              {'id': 41091, 'name': 'Kristen Wiig', 'cast_id': 12,'order': 2},
              {'id': 41092, 'name': 'Pedro Pascal', 'cast_id': 13, 'order': 3},
              {'id': 32, 'name': 'Robin Wright',  'cast_id': 78, 'order': 4}]


limit = 1
cast_limit = []
for dict in movie_cast:
    d = {key:value for (key,value) in dict.items() if dict['order'] < limit}
    cast_limit.append(d)
print(cast_limit)

current_result = [{'id': 90633,'name': 'Gal Gadot','cast_id': 0, 'order': 0},
                  {'id': 62064, 'name': 'Chris Pine','cast_id': 15, 'order': 1},{},{},{}]

desired_result = [{'id': 90633,'name': 'Gal Gadot','cast_id': 0, 'order': 0},
                 {'id': 62064, 'name': 'Chris Pine','cast_id': 15, 'order': 1}]

Try with this (you need a list comprehension, not a dict comprehension):

cast_limit = [dct for dct in movie_cast if dct['order'] < limit]

Ie, you need to filter out elements of the list, not elements of a dict.

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