Dado un diccionario, extrae todas las claves, cuyos valores son del tipo dado.
Entrada : test_dict = {‘gfg’: 2, ‘is’: ‘hola’, ‘for’: {‘1’: 3}, ‘geeks’: 4}, targ_type = int
Salida : [‘gfg’, ‘geeks ‘]
Explicación : gfg y geeks tienen valores enteros.Entrada : test_dict = {‘gfg’: 2, ‘es’: ‘hola’, ‘para’: {‘1’: 3}, ‘geeks’: 4}, targ_type = str
Salida : [‘es’]
Explicación : tiene valor de string.
Método #1: Usar loop + isinstance()
En esto, verificamos el tipo de datos usando isinstance() e iteramos todos los valores usando loop.
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))
Producción:
El diccionario original es: {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4} Las claves extraídas: [‘ gfg’, ‘mejor’, ‘geeks’]
Método n.° 2: usar la comprensión de listas + isinstance()
Similar al método anterior, abreviatura de una sola línea para resolver este problema utilizando la comprensión de listas.
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))
Producción:
El diccionario original es: {‘gfg’: 2, ‘is’: ‘hello’, ‘best’: 2, ‘for’: {‘1’: 3}, ‘geeks’: 4} Las claves extraídas: [‘ gfg’, ‘mejor’, ‘geeks’]
Método #3: Usando los métodos keys() y type()
Python3
# Python3 code to demonstrate working of # Extract Keys with specific Value Type # 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 i in test_dict.keys(): if type(test_dict[i]) is targ_type: res.append(i) # 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']
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA