Python – Limit the values to keys in a Dictionary List

PythonServer Side ProgrammingProgramming

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.

raja
Published on 20-Sep-2021 06:50:29
Advertisements