Python program to count the pairs of reverse strings

PythonServer Side ProgrammingProgramming

When it is required to count the pairs of reverse strings, a simple iteration is used.

Example

Below is a demonstration of the same

my_list = [{"Python": 8, "is": 1, "fun": 9}, {"Python": 2, "is": 9, "fun": 1}, {"Python": 5, "is": 10,"fun": 7}]

print("The list is :")
print(my_list)

result = {}
for dic in my_list:
   for key, value in dic.items():

      if key in result:
         result[key] = max(result[key], value)
      else:
         result[key] = value

print("The result is :")
print(result)

Output

The list is :
[{'Python': 8, 'is': 1, 'fun': 9}, {'Python': 2, 'is': 9, 'fun': 1}, {'Python': 5, 'is': 10, 'fun': 7}]
The result is :
{'Python': 8, 'is': 10, 'fun': 9}

Explanation

  • A list of dictionary is defined and is displayed on the console.

  • An empty dictionary is created.

  • The elements of the list are iterated over.

  • The items of the dictionary are iterated over.

  • If the key is present in the dictionary, then the maximum of key and value is assigned to result.

  • Otherwise, the value is placed in the result.

  • This is the result that is displayed on the console.

raja
Published on 16-Sep-2021 08:33:41
Advertisements