Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
Filtrar un diccionario de listas

Tengo un diccionario de la forma:

 {"level": [1, 2, 3], "conf": [-1, 1, 2], "text": ["here", "hel", "llo"]}

Quiero filtrar las listas para eliminar todos los elementos del índice i donde un índice en el valor "conf" no es >0.

Entonces, para el dict anterior, la salida debería ser esta:

 {"level": [2, 3], "conf": [1, 2], "text": ["hel", "llo"]}

Como el primer valor de conf no era > 0.

He intentado algo como esto:

 new_dict = {i: [a for a in j if a >= min_conf] for i, j in my_dict.items()}

Pero eso funcionaría solo para una tecla.

over 4 years ago · Santiago Trujillo
11 Respostas
Responde à pergunta

0

La estructura de los datos que está describiendo suena como si pudiera modelarse de manera más natural como un marco de datos de pandas : esencialmente está viendo sus datos como una cuadrícula 2-D, y desea filtrar las filas de esa cuadrícula en función del valor en una columna.

El siguiente fragmento hará lo que necesita usando un DataFrame como representación intermedia:

 import pandas as pd data = {"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]} df = pd.DataFrame(data) df = df.loc[df["conf"] > 0] result = df.to_dict(orient="list")

Producción:

 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}

Sin embargo, tenga en cuenta que si representa sus datos como un DataFrame en primer lugar y los mantiene en esa forma cuando haya terminado, esto se simplifica a,

 data = pd.DataFrame({ "level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"], }) result = data.loc[data["conf"] > 0]

Producción:

 level conf text 1 2 1 hel 2 3 2 llo

Que es más conciso, más expresivo y (en entradas grandes) más eficaz que cualquier solución de "dictado puro".

Si las otras operaciones que desea realizar con estos datos son similares (en el sentido de que realmente son operaciones de 'matriz 2D'), es probable que también se expresen de manera más natural en términos de DataFrames, por lo que mantendrá sus datos como un Es probable que DataFrame sea ventajoso frente a la conversión de nuevo a un dict.

over 4 years ago · Santiago Trujillo Relatório

0

Aquí hay una manera numpy de hacerlo:

 dct = {"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]} dct = {k: np.array(v) for k, v in d.items()} dct = {k: v[a['conf'] > 0].tolist() for k, v in a.items()}

Producción:

 >>> dct {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
over 4 years ago · Santiago Trujillo Relatório

0

Aquí hay una sola línea:

 dct = {k: [x for i, x in enumerate(v) if d['conf'][i] > 0] for k, v in d.items()}

Producción:

 >>> dct {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}

Con datos de muestra:

 d = {"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]
over 4 years ago · Santiago Trujillo Relatório

0

Creo que esto funcionará: para cada lista, filtraremos los valores donde conf es negativo, y luego conf en sí mismo.

 d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1","hel","llo"]} for key in d: if key != "conf": d[key] = [d[key][i] for i in range(len(d[key])) if d["conf"][i] >= 0] d["conf"] = [i for i in d["conf"] if i>=0] print(d)

Una solución más simple será (exactamente la misma pero usando la comprensión de listas, por lo que no necesitamos hacerlo por separado para conf y el resto:

 d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1","hel","llo"]} d = {i:[d[i][j] for j in range(len(d[i])) if d["conf"][j] >= 0] for i in d}

Salida: {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}

over 4 years ago · Santiago Trujillo Relatório

0

Mantendría los índices de elementos válidos (los mayores que 0) con:

 kept_keys = [i for i in range(len(my_dict['conf'])) if my_dict['conf'][i] > 0]

Y luego puede filtrar cada lista verificando si el índice de un determinado elemento en la lista está contenido en kept_keys :

 {k: list(map(lambda x: x[1], filter(lambda x: x[0] in kept_keys, enumerate(my_dict[k])))) for k in my_dict}

Producción:

 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
over 4 years ago · Santiago Trujillo Relatório

0

tratar:

 from operator import itemgetter def filter_dictionary(d): positive_indices = [i for i, item in enumerate(d['conf']) if item > 0] f = itemgetter(*positive_indices) return {k: list(f(v)) for k, v in d.items()} d = {"level": [1, 2, 3], "conf": [-1, 1, 2], "text": ["-1", "hel", "llo"]} print(filter_dictionary(d))

producción:

 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}

Primero traté de ver qué índices de 'conf' son positivos, luego con itemgetter seleccioné esos índices de los valores dentro del diccionario.

Versión más compacta + sin lista temporal usando expresión de generador en su lugar:

 def filter_dictionary(d): f = itemgetter(*(i for i, item in enumerate(d['conf']) if item > 0)) return {k: list(f(v)) for k, v in d.items()}
over 4 years ago · Santiago Trujillo Relatório

0

Prueba esto, simple y fácil de entender, especialmente para principiantes:

 a_dict = {"level": [1, 2, 3, 4, 5, 8], "conf": [-1, 1, -1, -2], "text": ["-1", "hel", "llo", "ai", 0, 9]} # iterate backwards over the list keeping the indexes for index, item in reversed(list(enumerate(a_dict["conf"]))): if item <= 0: for lists in a_dict.values(): del lists[index] print(a_dict)

Producción:

 {'level': [2, 5, 8], 'conf': [1], 'text': ['hel', 0, 9]}
over 4 years ago · Santiago Trujillo Relatório

0

a = {"level":[1,2,3,4], "conf": [-1,1,2,-1],"text": ["-1","hel","llo","test"]} # inefficient solution # for k, v in a.items(): # if k == "conf": # start_search = 0 # to_delete = [] #it will store the index numbers of the conf that you want to delete(conf<0) # for element in v: # if element < 0: # to_delete.append(v.index(element,start_search)) # start_search = v.index(element) + 1 #more efficient and elegant solution to_delete = [i for i, element in enumerate(a["conf"]) if element < 0] for position in list(reversed(to_delete)): for k, v in a.items(): v.pop(position)

y el resultado sera

 >>> a {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
over 4 years ago · Santiago Trujillo Relatório

0

Puede tener una función que determine qué índices mantener y reformular cada lista solo con esos índices:

 my_dict = {"level":[1,2,3], "conf":[-1,1,2],'text':["-1","hel","llo"]} def remove_corresponding_items(d, key): keep_indexes = [idx for idx, value in enumerate(d[key]) if value>0] for key, lst in d.items(): d[key] = [lst[idx] for idx in keep_indexes] remove_corresponding_items(my_dict, 'conf') print(my_dict)

Salida según lo solicitado

over 4 years ago · Santiago Trujillo Relatório

0

Lo resolví con esto:

 from typing import Dict, List, Any, Set d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1", "hel", "llo"]} # First, we create a set that stores the indices which should be kept. # I chose a set instead of a list because it has a O(1) lookup time. # We only want to keep the items on indices where the value in d["conf"] is greater than 0 filtered_indexes = {i for i, value in enumerate(d.get('conf', [])) if value > 0} def filter_dictionary(d: Dict[str, List[Any]], filtered_indexes: Set[int]) -> Dict[str, List[Any]]: filtered_dictionary = d.copy() # We'll return a modified copy of the original dictionary for key, list_values in d.items(): # In the next line the actual filtering for each key/value pair takes place. # The original lists get overwritten with the filtered lists. filtered_dictionary[key] = [value for i, value in enumerate(list_values) if i in filtered_indexes] return filtered_dictionary print(filter_dictionary(d, filtered_indexes))

Producción:

 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
over 4 years ago · Santiago Trujillo Relatório

0

Muchas buenas respuestas. Aquí hay otro enfoque de 2 pasos:

 mydict = {"level": [1, 2, 3], "conf": [-1, 1, 2], 'text': ["-1", "hel", "llo"]} for i, v in enumerate(mydict['conf']): if v <= 0: for key in mydict.keys(): mydict[key][i] = None for key in mydict.keys(): mydict[key] = [v for v in mydict[key] if v is not None] print(mydict)

Producción:

 {'level': [2, 3], 'conf': [1, 2], 'text': ['hel', 'llo']}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda