Python – Extract ith element of K key’s value
Last Updated :
12 Apr, 2023
Given a dictionary, extract ith element of K key’s value list.
Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]},
K = 'Gfg', i = 1
Output : 7
Explanation : 1st index of 'Gfg''s value is 7.
Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]},
K = 'best', i = 0
Output : 10
Explanation : 0th index of 'best''s value is 10.
Method 1: Using + get()
This is one of the ways in which this task can be performed. In this, we extract the key’s value using get() and then the value is extracted after checking for K being less than list length.
Python3
test_dict = { 'Gfg' : [ 6 , 7 , 3 , 1 ],
'is' : [ 9 , 1 , 4 ],
'best' : [ 10 , 7 , 4 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 'Gfg'
i = 2
temp = test_dict.get(K)
res = None
if temp and len (temp) > = i:
res = temp[i]
print ( "The extracted value : " + str (res))
|
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
Time complexity: O(1), as getting a value from a dictionary is an O(1) operation in Python, assuming the key exists.
Auxiliary space: O(1) as well, as the amount of memory used does not grow with the size of the dictionary.
Method 2: Using indexing
Python3
test_dict = { 'Gfg' : [ 6 , 7 , 3 , 1 ],
'is' : [ 9 , 1 , 4 ],
'best' : [ 10 , 7 , 4 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 'Gfg'
i = 2
res = test_dict[K][i]
print ( "The extracted value : " + str (res))
|
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
Time Complexity : O(N)
Auxiliary Space : O(1)
Method 3: Using Loops
- Initialize a variable result to None.
- Loop through the values of the K key in the dictionary using a for loop.
- For each value, check if the length of the value is greater than i.
- If the length is greater than i, set the result variable to the ith element of the value.
- Break out of the loop once the result variable has been set.
- Print the result.
Python3
test_dict = { 'Gfg' : [ 6 , 7 , 3 , 1 ],
'is' : [ 9 , 1 , 4 ],
'best' : [ 10 , 7 , 4 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 'Gfg'
i = 2
res = test_dict.get(K, [])[i]
print ( "The extracted value : " + str (res))
|
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
Time complexity: O(n), where n is the length of the list value of the K key.
Auxiliary space: O(1), since we only use a constant amount of extra space to store the result variable.
Method 4: using list comprehension.
Step-by-step approach:
- Initialize the dictionary test_dict.
- Print the original dictionary.
- Initialize K and i.
- Use list comprehension to extract the ith element of the K key’s value.
- Print the extracted value.
Below is the implementation of the above approach:
Python3
test_dict = { 'Gfg' : [ 6 , 7 , 3 , 1 ],
'is' : [ 9 , 1 , 4 ],
'best' : [ 10 , 7 , 4 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 'Gfg'
i = 2
res = [test_dict[key][i] for key in test_dict if key = = K][ 0 ]
print ( "The extracted value : " + str (res))
|
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
Time complexity: O(N), where N is the number of keys in the dictionary.
Auxiliary space: O(1), because only one variable is used to store the extracted value.
Method 5: Using the map() and filter() functions
STEPS :
- Start by initializing the dictionary test_dict.
Print the original dictionary using the print() function.
Initialize the variables K and i with the given values.
Use the map() function to extract the ith element of each value list in the dictionary. This is done by passing a lambda function to map() that accesses the ith element of the value list. Store the results in a new list extracted_values.
Use the filter() function to extract the value list for the given key K from the dictionary. This is done by passing a lambda function to filter() that checks if the current key is equal to K. Store the result in a new list filtered_values.
Extract the first element from filtered_values (which is the value list for the key K) and assign it to a variable value_list.
Extract the first element from extracted_values (which is the ith element of the value list for the key K) and assign it to a variable res.
Print the extracted value using the print() function.
Python3
test_dict = { 'Gfg' : [ 6 , 7 , 3 , 1 ],
'is' : [ 9 , 1 , 4 ],
'best' : [ 10 , 7 , 4 ]}
print ( "The original dictionary is : " + str (test_dict))
K = 'Gfg'
i = 2
extracted_values = list ( map ( lambda x: x[i], test_dict.values()))
filtered_values = list ( filter ( lambda x: x[ 0 ] = = K, test_dict.items()))
value_list = filtered_values[ 0 ][ 1 ]
res = extracted_values[ list (test_dict.keys()).index(K)]
print ( "The extracted value : " + str (res))
|
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary, due to the creation of two new lists extracted_values and filtered_values.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read