Python | Priority key assignment in dictionary
Last Updated :
23 Apr, 2023
Sometimes, while working with dictionaries, we have an application in which we need to assign a variable with a single value that would be from any of given keys, whichever occurs first in priority. Let's discuss certain ways in which this task can be performed.
Method #1 : Using loop This task can be performed in a brute force manner using loop. In this, we can just loop through the dictionary keys and priority list. If we find the key, we break and assign variable with it's value.
Python3
# Python3 code to demonstrate working of
# Priority key assignment in dictionary
# Using loop
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize priority keys
prio_list = ['best', 'gfg', 'CS']
# Using loop
# Priority key assignment in dictionary
res = None
for key in test_dict:
if key in prio_list :
res = test_dict[key]
break
# printing result
print("The variable value after assignment : " + str(res))
Output : The original dictionary : {'gfg': 6, 'is': 4, 'CS': 10, 'for': 2}
The variable value after assignment : 6
Method #2 : Using nested get() This problem can be solved by nesting the get() to get the value on priority. Even if it provides a cleaner and one-liner alternative to solve the problem, it is not recommended if we have more candidate keys to check for priority.
Python3
# Python3 code to demonstrate working of
# Priority key assignment in dictionary
# Using nested get()
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize priority keys
prio_list = ['best', 'gfg', 'CS']
# Using nested get()
# Priority key assignment in dictionary
res = test_dict.get(prio_list[0], test_dict.get(prio_list[1],
test_dict.get(prio_list[2])))
# printing result
print("The variable value after assignment : " + str(res))
OutputThe original dictionary : {'gfg': 6, 'is': 4, 'for': 2, 'CS': 10}
The variable value after assignment : 6
Method #3 : Using next()
This method uses the next() function to return the next item from an iterator that satisfies a certain condition. In this case, the condition is checking if the key is in the priority list.
Python3
# Python3 code to demonstrate working of
# Priority key assignment in dictionary
# Using next()
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize priority keys
prio_list = ['best', 'gfg', 'CS']
# Using next()
# Priority key assignment in dictionary
res = next((val for key, val in test_dict.items() if key in prio_list), None)
# printing result
print("The variable value after assignment : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original dictionary : {'gfg': 6, 'is': 4, 'for': 2, 'CS': 10}
The variable value after assignment : 6
Time complexity of O(n) where n is the number of items in the dictionary, because it iterates through all the items of the dictionary.
Auxiliary space of O(1) because they only use a single variable to store the result.
Method #4: Using list comprehension and get()
- Initialize the dictionary with key-value pairs.
- Create a list prio_list with the keys in the order of priority.
- Use a list comprehension to iterate over prio_list, getting the value associated with each key in the dictionary using the get() method, and return the first non-None value.
- Assign the result to a variable.
- Print the result.
Python3
# Initialize dictionary
test_dict = {'gfg' : 6, 'is' : 4, 'for' : 2, 'CS' : 10}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Initialize priority keys
prio_list = ['best', 'gfg', 'CS']
# Using list comprehension and get()
# Priority key assignment in dictionary
res = next(test_dict.get(key) for key in prio_list if key in test_dict)
# printing result
print("The variable value after assignment : " + str(res))
OutputThe original dictionary : {'gfg': 6, 'is': 4, 'for': 2, 'CS': 10}
The variable value after assignment : 6
Time complexity: O(n), where n is the number of keys in the priority list.
Auxiliary space: O(1), since we're only using a fixed number of variables regardless of the size of the input.
Similar Reads
Python - Combine dictionary with priority Sometimes, while working with dictionary data, we can have problem in which we need to combine two dictionaries. This is very common problem. But a variation of this can be combining dictionaries, and giving precedence to a particular dictionary if both the keys clash in dictionaries. Let's discuss
3 min read
Python - Maximum value assignment in Nested Dictionary Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign to the outer key, the item with maximum value in inner keys. This kind of problem can occur in day-day programming and web development domains. Let's discuss a way in which this task can be performed.
3 min read
Python Print Dictionary Keys and Values When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
2 min read
Add Same Key in Python Dictionary The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionar
3 min read
Add a key value pair to Dictionary in Python The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key.For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'fo
3 min read
Get Next Key in Dictionary - Python We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should b
2 min read