
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
Extract Key's Value from List and Dictionary in Python
When it is required to extract the value of key if the key is present in the list as well as the dictionary, a simple iteration and the ‘all’ operator are used.
Example
Below is a demonstration of the same −
my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", 'cool', 'object', 'oriented'] my_dictionary = {"Python" : 2, "fun" : 4, "learn" : 6} K = "Python" print("The value of K is ") print(K) print("The list is : " ) print(my_list) print("The dictionary is : " ) print(my_dictionary) my_result = None if all(K in sub for sub in [my_dictionary, my_list]): my_result = my_dictionary[K] print("The result is : ") print(my_result)
Output
The value of K is Python The list is : ['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach'] The dictionary is : {'Python': 2, 'fun': 4, 'learn': 6} The result is : 2
Explanation
A list of strings is defined and is displayed on the console.
A dictionary of values is defined and displayed on the console.
The value of K is defined and is displayed on the console.
A value is set to None.
The ‘all’ operator is used along with a simple iteration to check if the values present in the dictionary are present in the list.
If yes, the value will be assigned the ‘K’th element from the dictionary.
This value is displayed as the output on the console.
Advertisements