在 Python 中通过索引访问 OrderedDict 中的项目
Access items in an OrderedDict by index in Python
要按OrderedDict
索引访问项目:
- 使用该
dict.items()
方法获取字典项目的视图。 - 使用
list()
该类将视图对象转换为列表。 - 访问特定索引处的列表。
主程序
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # 👇️ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) print(dict_items[0]) # 👉️ ('name', 'bobbyhadz') print(dict_items[0][0]) # 👉️ name print(dict_items[0][1]) # 👉️ bobbyhadz
dict.items方法返回字典
项((键,值)对)的新视图。
主程序
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) # 👇️ odict_items([('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')]) print(my_dict.items())
但是,视图对象是不可订阅的(无法在特定索引处访问),因此我们不得不将视图对象转换为列表。
一旦我们有了 的项目列表OrderedDict
,我们就可以在特定索引处访问该列表。
主程序
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) print(dict_items[0]) # 👉️ ('name', 'bobbyhadz') print(dict_items[0][0]) # 👉️ name print(dict_items[0][1]) # 👉️ bobbyhadz
Python 索引是从零开始的,因此列表中的第一项的索引为,最后一项的索引为或。
0
-1
len(my_list) - 1
如果您只需要访问特定索引处的键或值,也可以使用dict.keys()
or方法。dict.values()
主程序
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_keys = list(my_dict.keys()) print(dict_keys) # 👉️ ['name', 'age', 'topic'] print(dict_keys[1]) # 👉️ age dict_values = list(my_dict.values()) print(dict_values) # 👉️ ['bobbyhadz', 30, 'Python'] print(dict_values[1]) # 👉️ 30
dict.keys方法返回字典键的
新视图。
dict.values方法返回字典
值的新视图。
如果您list.index()
需要获取OrderedDict
.
主程序
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_keys = list(my_dict.keys()) index = dict_keys.index('topic') print(index) # 👉️ 2 dict_values = list(my_dict.values()) print(dict_values[index]) # 👉️ Python
该list.index()
方法返回其值等于提供的参数的第一个项目的索引。
You can use list slicing if you need to get a slice of the dictionary’s items.
main.py
from collections import OrderedDict my_dict = OrderedDict( [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] ) dict_items = list(my_dict.items()) # 👇️ [('name', 'bobbyhadz'), ('age', 30), ('topic', 'Python')] print(dict_items) first_2 = dict_items[:2] print(first_2) # 👉️ [('name', 'bobbyhadz'), ('age', 30)]
The syntax for list slicing is my_list[start:stop:step]
.
The start
index is inclusive and the stop
index is exclusive (up to, but not
including).
If the
start
index is omitted, it is considered to be 0
, if the stop
index is omitted, the slice goes to the end of the list.The
OrderedDict
class is a subclass of dict
that remembers the order in which its entries were
added.
Note that as of Python 3.7, the standard dict
class is guaranteed to preserve
the insertion order as well.