
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
Count Pairs of Reverse Strings in Python
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.
Advertisements