gwe*_*o10 6 python dictionary ordereddictionary
如果字典中存在键,我想知道键的位置即数字索引.例如 :
如果字典包括:
{'test':{1,3},'test2':{2},'test3':{2,3}}
if 'test' in dictionary:
print(the index of that key)
Run Code Online (Sandbox Code Playgroud)
例如,输出为0.('test3'的输出为2 ......)
我现在正在使用字典,我猜我必须使用命令dict才能执行此操作,但我怎么能使用有序的dict呢?
谢谢你的帮助.
从 Python 3.6 开始,字典现在保留了插入顺序。因此,使用 Python 3.6+,您可以通过将 转换dict_keys为列表来获取索引。
dictionary = {'test':{1,3}, 'test2':{2}, 'test3':{2,3}}
if 'test' in dictionary:
print(list(dictionary).index('test'))
Run Code Online (Sandbox Code Playgroud)
作为另一个例子,下面演示了如何找到几个感兴趣的键的索引。
key_list = list(dictionary)
keys_of_interest = ['test2', 'test3']
for key in keys_of_interest:
print('key: {}, index: {}'.format(key, key_list.index(key)))
Run Code Online (Sandbox Code Playgroud)
输出将是
key: test2, index: 1
key: test3, index: 2
Run Code Online (Sandbox Code Playgroud)
对于Python <3.6,你不能这样做,因为Python中的字典没有顺序,因此项目没有索引.你可以使用一个OrderedDict从collections图书馆,虽然,而是和它传递的元组的元组:
>>> 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14790 次 |
| 最近记录: |