Python 提取特定值类型的键

Python 提取特定值类型的键

Python对一种称为关联数组的数据结构的实现更常见地称为字典。字典由一组键值对组成。每个键值组合对应一个键及其相应的值。

在本文中,我们将学习如何在Python中提取具有特定值类型的键。

使用的方法

以下是完成此任务的各种方法:

  • 使用for循环和isinstance()方法

  • 使用列表推导和isinstance()方法

  • 使用keys()和type()方法

示例

假设我们输入了一个 输入字典 。现在我们将

输入

inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
extractType = str

输出

['tutorials', 'codes']

在上面的输入字典中,具有str(string)类型的值为 ‘hi’‘user’ 。这些值对应的键分别为 ‘tutorials’‘codes’ 。因此提取这些键。

使用for循环和isinstance()方法

isinstance()函数

如果给定的对象是指定类型的,isinstance()函数返回 True ;否则,返回 False

如果type参数是 tuple ,则如果对象是元组中的一种类型,则返回 True

语法

isinstance(object, type)

参数

  • object - 一个需要检查的对象,判断是否属于该类。

  • type - 一个类型或类,或者是类型和/或类的元组。

步骤

以下是执行所需任务的算法/步骤:

  • 创建一个变量来存储具有多种数据类型的输入字典。

  • 打印输入字典。

  • 创建另一个变量来存储要提取的输入数据类型。

  • 初始化一个空列表来存储特定输入类型的结果键。

  • 使用for循环遍历输入字典的键和值,使用items()函数。

  • 使用if条件语句检查当前值类型是否等于输入提取类型,使用isinstance()函数。

  • 如果条件为true,则使用append()函数(将元素添加到列表末尾)将相应的键添加到结果键列表中。

  • 打印具有指定输入类型的输入字典的结果键。

示例

以下程序使用for循环和isinstance()方法从输入字典中返回给定输入值类型的键:

# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi',
   'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted
extractType = str
# storing resultant keys of input type
resultantKeys = []
# traversing through keys, values of input dictionary
for k, v in inputDict.items():
    # checking whether the current value type is equal to the input data type
    if isinstance(v, extractType):
        # appending that corresponding key to the resultant keys list
        resultantKeys.append(k)
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

输出

在执行上述程序时,将会生成以下输出:

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

使用列表推导式和isinstance()方法

当您希望基于现有列表的值构建一个新的列表时,列表推导式提供了一种更短/简洁的语法。

示例

以下程序使用列表推导式和isinstance()方法从输入的字典中返回给定输入值类型的键-值对:

# input dictionary having multiple datatypes 
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted 
extractType = str
# Using list comprehension to extract keys with string datatype
resultantKeys = [k for k, v in inputDict.items() if isinstance(v, extractType)]
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

输出

执行时,以上程序将生成以下输出 –

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

方法3 使用keys()和type()方法

keys()方法 − dict.keys()方法提供了一个视图对象,按插入顺序显示字典中所有键的列表。

type()函数 (返回对象的数据类型)。

步骤

执行所需任务的算法/步骤如下:

  • 使用 for循环 遍历输入字典的键,使用 keys() 函数。

  • 使用 if条件语句 检查当前值的类型是否等于输入的提取类型,使用type()函数。

  • 如果条件 为真 ,则使用 append()函数 将当前键添加到结果键列表中(将元素添加到列表末尾)。

  • 打印具有指定输入类型的输入字典的结果键。

示例

以下程序使用keys()和type()函数从输入字典中返回给定输入值类型的键:

# input dictionary having multiple datatypes
inputDict = {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
# printing input dictionary
print("Input dictionary:\n", inputDict)
# input datatype to be extracted
extractType = str
# storing resultant keys of input type
resultantKeys = []
# traversing through keys of input dictionary
for k in inputDict.keys():
  # checking whether the current value type of that corresponding key
  # is equal to the input extract type
    if type(inputDict[k]) is extractType:
        # appending the current key to the resultant list 
        resultantKeys.append(k)
# printing the resultant keys of the dictionary having the specified input type
print("Resultant keys of input dictionary with 'string' type:\n", resultantKeys)

输出

在执行时,上述程序将生成以下输出-

Input dictionary:
 {'hello': 5, 'tutorials': 'hi', 'users': 2, 'codes': 'user', 'python': [1, 2]}
Resultant keys of input dictionary with 'string' type:
 ['tutorials', 'codes']

结论

这篇文章教会了我们三种不同的方法来提取具有特定值类型的键。此外,我们还学会了使用type()函数来确定变量的类型,以及使用isinstance()方法来比较两种数据类型。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程