If a key is present in a dictionary, I want to know what position the key is in i.e the numerical index. For example :
if the dictionary consists of :
{'test':{1,3},'test2':{2},'test3':{2,3}}
if 'test' in dictionary:
print(the index of that key)
The output would be 0 for example. (The output would be 2 for 'test3'...)
I'm using a dictionary at the moment, I'm guessing I'd have to use an ordered dict
to do this, but how can I do it using an ordered dict
?
Thanks for any help.
Use the list[index] function to get index numbers from the dictionary. It will return the key and also use the items() function to return a collection from a dictionary.
In this article we will learn how to create a dictionary from another frequently used python collection namely list. An index or key is not part a list content. But in dictionary we need to have a key or index attached to every element which is referred as value.
Method 1: Get the key by value using list comprehension. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list to get the key from a value in Dictionary.
get() method is used in Python to retrieve a value from a dictionary. dict. get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.
For Python <3.6, you cannot do this because dictionaries in Python have no order to them, so items don't have an index. You could use an OrderedDict
from the collections
library instead though, and pass it a tuple of tuples:
>>> import collections
>>> d = collections.OrderedDict((('test',{1,3}),('test2',{2}),('test3',{2,3})))
>>> d.keys().index('test3') # Replace with list(d.keys()).index("test3") for Python 3
2
As of Python 3.6, dictionaries now preserves the insertion order. So using Python 3.6+, you could get the index by converting the dict_keys
to a list.
dictionary = {'test':{1,3}, 'test2':{2}, 'test3':{2,3}}
if 'test' in dictionary:
print(list(dictionary).index('test'))
As another example, the following demonstrates how to find the index for a few keys of interest.
key_list = list(dictionary)
keys_of_interest = ['test2', 'test3']
for key in keys_of_interest:
print('key: {}, index: {}'.format(key, key_list.index(key)))
The output from this would be
key: test2, index: 1
key: test3, index: 2
You can just build an index :
ind= {k:i for i,k in enumerate(dictionary.keys())}
then ind['test3']
will be 2, with O(1) access time.
This is robust while keys are fixed. If you add/remove keys, you have to rebuild the index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With