Python | Select dictionary with condition given key greater than k

Python | Select dictionary with condition given key greater than k

Let's say you have a list of dictionaries and you want to select dictionaries where a given key has a value greater than k. You can achieve this using a list comprehension.

Here's how you can do it:

# Sample list of dictionaries data = [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 5, 'name': 'Charlie'}, {'id': 8, 'name': 'David'}, {'id': 3, 'name': 'Eve'} ] k = 3 # Select dictionaries where 'id' is greater than k selected_data = [d for d in data if d['id'] > k] print(selected_data) 

This code will output:

[{'id': 5, 'name': 'Charlie'}, {'id': 8, 'name': 'David'}] 

In the code above, we use a list comprehension to iterate over each dictionary d in the data list. The condition d['id'] > k ensures we only select dictionaries where the value associated with the 'id' key is greater than k.


More Tags

ohhttpstubs sql-insert mms error-checking domain-name calculated-field ruby-on-rails-3 cx-oracle auto-increment cobertura

More Programming Guides

Other Guides

More Programming Examples