
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Limit Values to Keys in a Dictionary List in Python
When it is required to limit the values to keys in a list of dictionary, the keys are accessed and the ‘min’ and ‘max’ methods are used to limit the values.
Example
Below is a demonstration of the same
my_list = [{"python": 4, "is": 7, "best": 10},{"python": 2, "is": 5, "best": 9},{"python": 1, "is": 2, "best": 6}] print("The list is :") print(my_list) my_result = dict() keys = list(my_list[0].keys()) for my_elem in keys: my_result[my_elem] = [min(sub[my_elem] for sub in my_list), max(sub[my_elem] for sub in my_list)] print("The result is :") print(my_result)
Output
The list is : [{'python': 4, 'is': 7, 'best': 10}, {'python': 2, 'is': 5, 'best': 9}, {'python': 1, 'is': 2, 'best': 6}] The result is : {'python': [1, 4], 'is': [2, 7], 'best': [6, 10]}
Explanation
A list of dictionary is defined and is displayed on the console.
An empty dictionary is created.
The keys of the list of dictionary are converted into a list and stored in a variable.
These values are iterated over and the minimum and maximum of values are obtained.
This is done by iterating over the elements in the list.
This is displayed as output on the console.
Advertisements