Python provides various ways to get the index of the specified key of the dictionary. In dictionaries, elements are presented in the form of key:value pairs and all keys are associated with their corresponding values. Dictionaries are unordered and mutable You can access, remove, and add elements of a dictionary by using its keys in several ways. You can get the index position of a certain key in a dictionary using different functions of Python.
In this article, I will explain how to get the index of a specified key in a dictionary using different ways with examples.
1. Quick Examples of Getting Index of Specified Key in Dictionary
Below are some quick examples of how to get a key index in a dictionary. These should give you an idea of how to get an index in the dictionary and the below sections explain in detail.
# Below are the examples of getting the index of specified Key
# Initialize dictionary
my_dict = {‘course’ : ‘Python’, ‘fee’ : 4500, ‘duration’ : ’45 days’}
# Example 1: Get the index position of the specified key
# in Dictionary using list() and index()
# Initialize the index
index = None
if “fee” in my_dict:
index = list(my_dict).index(“fee”)
print(“Index of fee:”, index)
# Example 2: Iterate through the dictionary to get
# the index of the specified key
for i, key in enumerate(my_dict.keys()):
if key == index_key:
index = i
break
print(“Index of specified key is :”, index)
# Example 3: Get the index position of specified key
# using list comprehension and enumerate()
index = [idx for idx, key in enumerate(list(my_dict.items())) if key[0] == index_key]
print(“Index of duration : “, index)
# Example 4: Get specified key and value by index in Dictionary
index = 2
key, value = list(my_dict.items())[index]
print(“Get key of specified index:”, key)
print(“Get value of specified index:”, value)
What is Python Dictionary
A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.
Moreover, dictionaries are mutable data types, which means that you can be added, deleted, and updated their key:value pairs.
A value can be any data type such as a number(int, float), a string, a list, a tuple, or even another dictionary and it allows duplicates. On the other hand, keys are immutable types such as string, numbers(int, float), and tuple and it doesn’t allow duplicates. In case, you add duplicates, which will update the existing keys of the Python dictionary.
2. Get Index of Specified Key using list.index() Function
You can use the list() function along with index() function to get the index position of specified key in dictionary. First, using list() function you can convert the dictionary to a list of keys. Then use the list.index()function to get the index position of the specified key in the dictionary.
Pass the specified key into the index() function, it will check the passed key is exist in the list and return the index position of the passed key. If it is not exist, will return the ValueError.
# Get index position of the specified key
# in Dictionary using list() and index()
# Initialize dictionary
my_dict = {‘course’ : ‘Python’, ‘fee’ : 4500, ‘duration’ : ’45 days’}
print(“Dictionary is : “, my_dict)
# Initialize the index
index = None
if “fee” in my_dict:
index = list(my_dict).index(“fee”)
print(“Index of fee:”, index)
# Access key using the index of dictionary
print(“Access key using index:”, list(my_dict)[1])
# Access value using the index of dictionary
print(“Access value using index:”, list(my_dict.values())[1])
Yields below output.
3. Get Index of Key in Dictionary using For Loop
Alternatively, you can use for loop to iterate over the dictionary and get the index position of the specified key. First, assign the index as None and index_key as “course” then, use dict.keys() function to get the keys of the dictionary as a list then iterate over enumerate of dictionary keys, each iteration checks if the specified key exists in the key. If it exists corresponding counter value(index) adds to the index variable. Finally, you can get the index position of the specified key.
# Initialize dictionary
my_dict = {‘course’ : ‘Python’, ‘fee’ : 4500, ‘duration’ : ’45 days’}
print(“Dictionary is : “, my_dict)
index_key = “course”
index = None
# Iterate through the dictionary to get
# the index of the specified key
for i, key in enumerate(my_dict.keys()):
if key == index_key:
index = i
break
print(“Index of specified key is :”, index)
Yields below output.
4. Using List Comprehension & enumerate() to Get the Index
You can use list comprehension to get the list of specified key index position. You can use enumerate() function to get the index values along with corresponding items of the passed sequence of key/value pair, then check if the key[0] is index_key. It will return the list of specified key index position.
# Initialize dictionary
my_dict = {‘course’ : ‘Python’, ‘fee’ : 4500, ‘duration’ : ’45 days’}
print(“Dictionary is : “, my_dict)
index_key = ‘duration’
# Get the index position of specified key
# using list comprenesion and enumerate()
index = [idx for idx, key in enumerate(list(my_dict.items())) if key[0] == index_key]
print(“Index of duration : “, index)
# Output:
# Dictionary is : {‘course’: ‘Python’, ‘fee’: 4500, ‘duration’: ’45 days’}
# Index of duration : [2]
5. Get Python Dictionary Items by Index
You can use the dict.items() function along with index attribute to get a dictionary key-value pair by index. You can use dict.items() function to get the view object of the key/value pair as a tuple of a list. Apply the specified index over the list of dict.items(), it will return the corresponding key or value of the specified index.
# Get specified key and value by index in Dictionary
# Initialize dictionary
my_dict = {‘course’ : ‘Python’, ‘fee’ : 4500, ‘duration’ : ’45 days’}
print(“Dictionary is : “, my_dict)
index = 2
key, value = list(my_dict.items())[index]
print(“Get key of specified index:”, key)
print(“Get value of specified index:”, value)
# Output:
# Dictionary is : {‘course’: ‘Python’, ‘fee’: 4500, ‘duration’: ’45 days’}
# Get key of specified index: duration
# Get value of specified index: 45 days
6. Conclusion
In this article, I have explained how to get the index position of a specified key in a dictionary using different ways with examples. And also explained using an index how we can access the corresponding key or value of the dictionary.
Happy learning!!
Python provides various ways to get the index of the specified key of the dictionary. In dictionaries, elements are presented in the form of key:value pairs and all keys are associated with their corresponding values. Dictionaries are unordered and mutable You can access, remove, and add elements of a dictionary by using its keys in several ways. Read More Python, Python Tutorial, Pending review by admin, Python Dictionary Examples