Python - 提取具有特定值类型的键
给定一个字典,提取所有键,其值属于给定类型。
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = int
Output : [‘gfg’, ‘geeks’]
Explanation : gfg and geeks have integer values.
Input : test_dict = {‘gfg’ : 2, ‘is’ : ‘hello’, ‘for’ : {‘1’ : 3}, ‘geeks’ : 4}, targ_type = str
Output : [‘is’]
Explanation : is has string value.
方法 #1:使用循环 + isinstance()
在这里,我们使用isinstance()检查数据类型,并使用循环迭代所有值。
Python3
# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
# Using loop + isinstance()
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing type
targ_type = int
res = []
for key, val in test_dict.items():
# checking for values datatype
if isinstance(val, targ_type):
res.append(key)
# printing result
print("The extracted keys : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
# Using list comprehension + isinstance()
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing type
targ_type = int
# one-liner to solve the problem
res = [key for key, val in test_dict.items() if isinstance(val, targ_type)]
# printing result
print("The extracted keys : " + str(res))
输出:
The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}
The extracted keys : [‘gfg’, ‘best’, ‘geeks’]
方法 #2:使用列表理解+ isinstance()
与上述方法类似,使用列表理解来解决此问题的单行速记。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Keys with specific Value Type
# Using list comprehension + isinstance()
# initializing dictionary
test_dict = {'gfg': 2, 'is': 'hello', 'best': 2, 'for': {'1': 3}, 'geeks': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing type
targ_type = int
# one-liner to solve the problem
res = [key for key, val in test_dict.items() if isinstance(val, targ_type)]
# printing result
print("The extracted keys : " + str(res))
输出:
The original dictionary is : {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4}
The extracted keys : [‘gfg’, ‘best’, ‘geeks’]