在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]