在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]热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西