在 Python 中获取字典中的最后一个键

使用 list() 函数获取字典中的最后一个键,例如 last_key = list(my_dict)[-1]。 list() 函数将字典转换为键列表,我们可以在其中访问索引 -1 处的元素以获取最后一个键。

my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}

last_key = list(my_dict)[-1]
print(last_key)  # ?️ country

print(my_dict[last_key]) # ?️ Austria

first_key = list(my_dict)[0]
print(first_key)  # ?️ id

在 Python 中获取字典中的最后一个键

我们使用 list() 函数来获取字典中的最后一个键。

list() 函数将字典转换为键列表。

my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}

print(list(my_dict))  # ?️ ['id', 'name', 'country']

最后一步是访问索引 -1 处的列表项。

my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}

print(list(my_dict))  # ?️ ['id', 'name', 'country']

last_key = list(my_dict)[-1]
print(last_key)  # ?️ country

print(my_dict[last_key]) # ?️ Austria

first_key = list(my_dict)[0]
print(first_key)  # ?️ id

从 Python 3.7 开始,标准 dict 类保证保留键的顺序。

负索引可用于倒数,例如 my_list[-1] 返回列表中的最后一项,my_list[-2] 返回倒数第二项。

Python 索引是从零开始的,因此列表中的第一项的索引为 0,最后一项的索引为 -1 或 len(my_list) – 1。

或者,我么可以使用 dict.keys() 方法。

要获取字典中的最后一个键:

  1. 使用 dict.keys() 方法获取字典键的视图。
  2. 使用 list() 函数将视图转换为列表。
  3. 访问索引 -1 处的列表项以获取最后一个键。
my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}


last_key = list(my_dict.keys())[-1]
print(last_key)  # ?️ 'country'

print(my_dict[last_key])  # ?️ 'Austria'

dict.keys 方法返回字典键的新视图。

my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}


# ?️ dict_keys(['id', 'name', 'country'])
print(my_dict.keys())

# ?️ ['id', 'name', 'country']
print(list(my_dict.keys()))

dict_keys 对象不可下标,因此我们无法在特定索引处访问它。

我们可以将对象转换为列表来解决这个问题。

my_dict = {
    'id': 1,
    'name': 'Alice',
    'country': 'Austria'
}


last_key = list(my_dict.keys())[-1]
print(last_key)  # ?️ 'country'

在这种情况下,我们不必使用 my_dict.keys() 方法,因为我们只需将字典传递给 list() 函数即可获取其键的列表。

但是,我们经常会看到这种方法用于获取字典中的最后一个键。

如果我们使用的版本早于 Python 3.7,则不会保留字典中键的顺序,我们必须使用 OrderedDict。

from collections import OrderedDict

my_dict = OrderedDict(
    [('id', 1), ('name', 'Alice'), ('country', 'Austria')]
)

last_key = list(my_dict)[-1]
print(last_key)  # ?️ 'country'

list() 函数也可用于将 OrderedDict 的键转换为列表。

from collections import OrderedDict

my_dict = OrderedDict(
    [('id', 1), ('name', 'Alice'), ('country', 'Austria')]
)

print(list(my_dict)) # ?️ ['id', 'name', 'country']

在 Python 中获取字典中的最后一个键

最后一步是访问索引 -1 处的键以获取最后一个键。