在Python中获取字典键作为列表
对于许多程序来说,从字典中获取键是重要的输入,其他依赖于此字典的程序会用到它。在本文中,我们将学习如何将键捕获为列表。
使用dict.keys
这是访问键的一种非常直接的方法。此方法作为内置方法可用。
示例
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ",Adict)
print(list(Adict.keys()))输出
运行以上代码得到以下结果:
The given dictionary is :
{1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'}
[1, 2, 3, 4]使用*
* 可以应用于任何可迭代对象。因此,可以使用 * 直接访问字典的键,这也称为解包。
示例
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ",Adict)
print([*Adict])输出
运行以上代码得到以下结果:
The given dictionary is :
{1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'}
[1, 2, 3, 4]使用itemgetter
itemgetter(i) 构造一个可调用的函数,它以字典、列表、元组等可迭代对象作为输入,并从中获取第 i 个元素。因此,我们可以使用此方法结合 map 函数来获取字典的键,如下所示。
示例
from operator import itemgetter
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'}
print("The given dictionary is :\n ",Adict)
print(list(map(itemgetter(0), Adict.items())))输出
运行以上代码得到以下结果:
The given dictionary is :
{1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'}
[1, 2, 3, 4]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP