简体   繁体   中英

Get index in dictionary, not a key value

I have a dictionary like this:

header= {'f1': 13, 'f2': 7, 'f3': 45};

As you see, header['f2'] = 7 has the minimum value and this item is the second in header (its index is 1).

What I do?

I have try this code to get the index of minimum item in header (here 1) but it returns the key value:

index = min(header)

Output:

f2

What I want?

I want to get the index of the minimum item in the dictionary, How can i do that?

Dictionaries do not have indices

Even in Python 3.6+ (officially 3.7+), where dictionaries are insertion ordered , you cannot extract a key or value directly by position. The same is true for collections.OrderedDict . See also: Accessing dictionary items by position in Python 3.6+ efficiently .

min + enumerate

Assuming Python 3.6+, you can extract the position of a key / value based on insertion ordering via iteration. In this case, you can use min with a custom lambda function:

header = {'f1': 13, 'f2': 7, 'f3': 45}

min_idx, (min_key, min_val) = min(enumerate(header.items()), key=lambda x: x[1][1])

print((min_idx, min_key, min_val))

(1, 'f2', 7)

Using header.values() returns a list of just the values of your dictionary:

>>> header= {'f1': 13, 'f2': 7, 'f3': 45}
>>> header.values()
[13, 7, 45]
>>> print(min(header.values()))
7

EDIT: Sorry, you wanted the corresponding key. Here's one way to do it, without having to include any other special libraries:

print(header.keys()[header.values().index(min(header.values()))])

Although dictionaries are not ordered in Python, lists are, and the lists you get from .keys() and .values() line up with each other.

list(header.values()).index(min(header.values()))

这将返回字典中最小值的索引。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM