Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Filter a dictionary of lists

I have a dictionary of the form:

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

I want to filter the lists to remove every item at index i where an index in the value "conf" is not >0.

So for the above dict, the output should be this:

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

As the first value of conf was not > 0.

I have tried something like this:

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

But that would work just for one key.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

try:

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))

output:

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

I tried to first see which indices of 'conf' are positive, then with itemgetter I picked those indices from values inside the dictionary.

More compact version + without temporary list using generator expression instead:

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 Report

0

I would keep the indexes of valid elements (those greater than 0) with:

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

And then you can filter each list checking if the index of a certain element in the list is contained in 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}

Output:

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

0

Here's a one-liner:

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

Output:

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

With sample data:

d = {"level":[1,2,3], "conf":[-1,1,2], "text":["here","hel","llo"]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!