简体   繁体   English

如何有效地从SortedDict获取键的索引和值?

[英]How do I efficiently get the index and value for a key from SortedDict?

Given a collection that is ordered and keyed (like OrderedDict or SortedContainers SortedDict) I want to do the following: 给定一个有序且有键的集合(例如OrderedDict或SortedContainers SortedDict),我想执行以下操作:

d['first'] = 'hi'
d['second'] = 'there'
d['third'] = 'world'
(ix, value) = d.get_index_and_value('second')
assert d.iloc[ix + 1] == 'third'
# or list(d.keys())[ix + 1] with OrderedDict

however I cannot see an efficient way to get both the index and the value given a key ( (ix, value) = d.get_index_and_value('second') ). 但是我看不到一种有效的方式来获取给定键的索引和值( (ix, value) = d.get_index_and_value('second') )。

Is this possible with SortedDict, or another container? 使用SortedDict或其他容器是否可能?

In practice, my keys are a sortable collection (dates) if that means there is a better container I could use. 在实践中,如果这意味着我可以使用更好的容器,那么我的密钥就是一个可排序的集合(日期)。

You can use the index method of keys : 您可以使用keysindex方法:

ix, value = d.keys().index('second'), d['second']

this will return 这将返回

(1, 'there')

If you don't want to repeat yourself, you can make this a function, or extend OrderedDict to include this as a method: 如果您不想重复自己,可以使它成为一个函数,或者扩展OrderedDict以将其作为方法包括在内:

def get_index_and_value(d, key):
    return d.keys().index(key), d[key]

print(get_index_and_value(d, 'second')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更有效地获取列表中所有记录最高数字的索引值? - How do I more efficiently get a list's index values for all its record highest numbers? 如何从每个键有多个值的字典中的键中获取特定值? - How do I get a specific value from a key in a dictionary with multiple values per key? SortedDict:按python中的值排序 - SortedDict: Sort by value in python 如何在 python 字典中的特定索引处获取密钥? - How do i get the key at a specific index in a python dictionary? 如何获取列中最大值的索引,以便我可以从不同列但同一行中获取值? - How do I get the Index of the max value in a column so I can get a value from a different column but same row? Python:如何从BaseHTTPRequestHandler HTTP POST处理程序获取键/值对? - Python: How do I get key/value pairs from the BaseHTTPRequestHandler HTTP POST handler? 如何从字典 python 列表中第一个元素的键中获取值? - How do i get a value from a key in the first element in a list with dictionaries python? 如何使用 python 中的索引从 json 列表中获取值? - How do I get a value from a json list using an index in python? 如何有效地将角度(以弧度为单位)转换为从 0 到 7 的指数? - How can I efficiently convert an angle (in radian) to an index from 0 to 7? 如何通过 django 中的外键连接从 object 获取特定值? - How do I get a specific value from an object through foreign key connection in django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM