-1
a = [{lang: 'english', count: 15}, {lang: 'spanish', count: 25}]
b = ['spanish', 'english']

I would like to check if the items in b list appears in a - list of dicts. (specifically in lang key).

if we have a match as we have in my example (both of b list items appears in a list of dicts), I would like to return a new list of dict with only the item that have the max count.

For this example:

[{lang: 'spanish', count: 25}]

Can you please help me with this? Thanks!

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
lennyb
  • 17
  • 3
  • 1
    What have you tried so far based on your own research, and what went wrong with your attempts? A [mcve] should include your code and a description of the specific problem with that code – G. Anderson Jun 06 '22 at 16:14
  • Shouldn't `lang` and `count` be in quotes? – The Thonnu Jun 06 '22 at 16:15

1 Answers1

0

Use max() with a key argument to extract the 'count' value and a filter to limit it to the languages in b:

>>> b = ['spanish', 'english']
>>> a = [{'lang': 'english', 'count': 15}, {'lang': 'spanish', 'count': 25}]
>>> [max((d for d in a if d['lang'] in b), key=lambda d: d['count'])]
[{'lang': 'spanish', 'count': 25}]
Samwise
  • 68,105
  • 3
  • 30
  • 44