Reputation: 425
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.
Upvotes: 25
Views: 89947
Reputation: 343
This seems to work for me:
def list_has_dict_by_key(_lst: list[dict], _key: any):
fn = lambda lst, key: [i for i, d in enumerate(lst) if key in d.keys()] or [-1]
return fn(_lst, _key).pop
Upvotes: 0
Reputation: 1183
You can just convert dict.keys() to a list and then index the list
keys = list(dictionary.keys())
index = keys.index("test")
indexing values that are not in the list will result in ValueError
keys.index("test5")
ValueError: "test5" is not in list
Upvotes: 3
Reputation: 3414
With python 3.6 or later, with dicts preserving insertion order, then you can do it in one line, with it returning 'None' if the key isn't in the dictionary:
key_index = list(my_dictionary).index(the_key) if the_key in my_dictionary else None
Upvotes: 2
Reputation: 18624
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
Upvotes: 21
Reputation: 11837
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
Upvotes: 14
Reputation: 18668
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.
Upvotes: 3
Reputation: 5534
Unfortunately, such a thing is not possible because of how dictionaries are constructed in python. These data structures are inherently unordered.
To get the functionallity you want you must use a different data structure, such as OrderedDict
Upvotes: 0