Python - Value limits to keys in Dictionaries List

Python - Value limits to keys in Dictionaries List

In this tutorial, you will learn how to set limits on the values corresponding to specific keys in a list of dictionaries. This can be helpful when you want to ensure that values for certain keys do not exceed or fall below particular thresholds.

Objective:

Given a list of dictionaries, limit the values for specific keys within a defined range.

Example:

Suppose we have the following list of dictionaries containing student marks:

students = [ {"name": "John", "marks": 105}, {"name": "Doe", "marks": 85}, {"name": "Jane", "marks": -5} ] 

For our use case, the marks should be in the range 0 to 100. Any value below 0 should be set to 0, and any value above 100 should be set to 100.

The desired output is:

[ {"name": "John", "marks": 100}, {"name": "Doe", "marks": 85}, {"name": "Jane", "marks": 0} ] 

Steps:

  1. Iterate Through Each Dictionary: Loop through each dictionary in the list.

  2. Check the Value for Specific Key: Check the value corresponding to the desired key.

  3. Adjust the Value If Necessary: If the value exceeds or is below the defined limits, adjust it.

Code:

Let's go through the implementation:

def limit_values(data, key, min_value, max_value): for record in data: # Ensure the key exists in the dictionary if key in record: # Set value limits if record[key] < min_value: record[key] = min_value elif record[key] > max_value: record[key] = max_value return data # Test the function students = [ {"name": "John", "marks": 105}, {"name": "Doe", "marks": 85}, {"name": "Jane", "marks": -5} ] print(limit_values(students, "marks", 0, 100)) 

Output:

[ {"name": "John", "marks": 100}, {"name": "Doe", "marks": 85}, {"name": "Jane", "marks": 0}] 

Explanation:

  • The function limit_values accepts a list of dictionaries (data), a key whose values you want to limit, and the min_value and max_value range limits.

  • We iterate through each record (dictionary) in the list.

  • For each dictionary, if it contains the desired key, we check the associated value and adjust it if it's outside the allowed range.

Conclusion:

This tutorial showed how to set value limits for specific keys in a list of dictionaries. Such operations are useful in data preprocessing tasks where certain values might need to be within a specified range.


More Tags

dll date svg.js ios7 angular-material multiple-variable-return google-cloud-endpoints blender remote-debugging gnu-make

More Programming Guides

Other Guides

More Programming Examples