Python | Extract key-value of dictionary in variables
Last Updated :
26 Apr, 2023
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let’s discuss certain ways in which this can be done.
Method #1: Using items() This problem can be solved using the items function which does the task of extracting a key-value pair and using the 0th index gives us the first key-value pair. Works only in Python2.
Python
test_dict = { 'gfg' : 1 }
print ("The original dictionary : " + str (test_dict))
key, val = test_dict.items()[ 0 ]
print ("The 1st key of dictionary is : " + str (key))
print ("The 1st value of dictionary is : " + str (val))
|
Output :
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1
Time complexity: O(1), as the operation of extracting the key value of a dictionary using items() is constant time, i.e., it takes O(1) time to extract the first item in the dictionary.
Auxiliary space: O(1), as it only requires a constant amount of memory to store the variables key and val and the operation of extracting the first item from the dictionary does not create any additional memory overhead.
Method #2: Using iter() + next() The combination of above functions can be used to perform this particular task. It uses iterators to perform this task. The next() is used to fetch the pairs till dictionary is exhausted. It works with Python3.
Python3
test_dict = { 'gfg' : 1 }
print ("The original dictionary : " + str (test_dict))
key, val = next ( iter (test_dict.items()))
print ("The 1st key of dictionary is : " + str (key))
print ("The 1st value of dictionary is : " + str (val))
|
Output :
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3 : Using keys(),values()
Python3
test_dict = { 'gfg' : 1 }
print ( "The original dictionary : " + str (test_dict))
key = list (test_dict.keys())[ 0 ]
val = list (test_dict.values())[ 0 ]
print ( "The 1st key of dictionary is : " + str (key))
print ( "The 1st value of dictionary is : " + str (val))
|
Output
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1
Time Complexity: O(N)
Auxiliary Space: O(1)
Method #4: Using a for loop to iterate over dictionary
Step-by-step approach:
- Initialize dictionary
- Create two empty variables, key and val
- Use a for loop to iterate over the dictionary and assign the key-value pairs to the variables key and val respectively
- Print the result
Python
test_dict = { 'gfg' : 1 }
print ( "The original dictionary : " + str (test_dict))
key, val = None , None
for k, v in test_dict.items():
key, val = k, v
break
print ( "The 1st key of dictionary is : " + str (key))
print ( "The 1st value of dictionary is : " + str (val))
|
Output
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1
Time Complexity: O(n) where n is the number of key-value pairs in the dictionary
Auxiliary Space: O(1)
Method 5 : using list conversion.
we initializes a dictionary with one key-value pair and prints the original dictionary. Then, it uses the list conversion method to extract the first key-value pair of the dictionary and assigns them to the variables ‘key’ and ‘val’. Finally, it prints the extracted key and value.
Python3
test_dict = { 'gfg' : 1 }
print ( "The original dictionary : " + str (test_dict))
key, val = list (test_dict.items())[ 0 ]
print ( "The 1st key of dictionary is : " + str (key))
print ( "The 1st value of dictionary is : " + str (val))
|
Output
The original dictionary : {'gfg': 1}
The 1st key of dictionary is : gfg
The 1st value of dictionary is : 1
The time complexity for all the methods mentioned above is O(1), as we are only accessing the first element of the dictionary, which takes constant time.
The space complexity is also constant, as we are only using a constant amount of memory to store the key-value pair.
Similar Reads
Python | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in
5 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name" Then, the unique value
4 min read
Extract Subset of Key-Value Pairs from Python Dictionary
In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filter
4 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and donât care about keys. This is yet another essential utility and solution to it should be known and discussed. Letâs perform this task through certain methods. Method
4 min read
Variable Operations Dictionary Update - Python
The task of performing variable operations in a dictionary in Python involves updating the values associated with specific keys based on certain operations. For example, consider a scenario where x = 6 and y = 7. The goal could be to store the sum of x and y under the key 'Gfg' and the product of x
3 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python - Extracting Kth Key in Dictionary
Many times, while working with Python, we can have a situation in which we require to get the Kth key of dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kind. This is useful for Python version 3.8 +, where key ordering are similar as inserti
4 min read
Python | Sum values for each key in nested dictionary
Given a nested dictionary and we have to find sum of particular value in that nested dictionary. This is basically useful in cases where we are given a JSON object or we have scraped a particular page and we want to sum the value of a particular attribute in objects. Code #1: Find sum of sharpness v
2 min read
Extract Dictionary Values as a Python List
To extract dictionary values from a list, we iterate through each dictionary, check for the key's presence, and collect its value. The result is a list of values corresponding to the specified key across all dictionaries.For example, given data = {'a': 1, 'b': 2, 'c': 3}, the output will be [1, 2, 3
3 min read