迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/04/09 浏览次数:

使用 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,最后一项的索引为 -1len(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 处的键以获取最后一个键。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便