DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
0 votes

This is working. It was giving me an error but I've solved it. I'll leave it here for reviewing. How could I write def filter_dict_list as a one-liner?

mymodule.py

def filter_dict(d: dict, keys: list[str]) -> dict:
    return {k: d[k] for k in keys}


def filter_dict_list(l: list[dict], keys: list[str]):
    res = []
    for d in l:
        res.append(filter_dict(d, keys))
    return res

mymodule_test.py

import unittest

import mymodule


class TestFilter(unittest.TestCase):
    def test_filter_dict(self) -> None:
        d = {"a": 1, "b": 2, "c": 3}
        keys = ["b", "c"]
        expected = {"b": 2, "c": 3}
        actual = mymodule.filter_dict(d, keys)
        self.assertEqual(expected, actual)

    def test_filter_dict_list(self) -> None:
        l = [{"a": 1, "b": 2, "c": 3}, {"a": 1, "b": 2, "c": 3}]
        keys = ["b", "c"]
        expected = [{"b": 2, "c": 3}, {"b": 2, "c": 3}]
        actual = mymodule.filter_dict_list(l, keys)
        self.assertEqual(expected, actual)


if __name__ == "__main__":
    unittest.main()
by
edited by
0

What is the question here?

0

I had a silly error but I found it and removed the question. I left the code for reviewing in case it can be improved. I've added a question now to make it more objective.

1 Answer

+1 vote
 
Best answer
def filter_dict(d, keys):
    return { k: d[k] for k in keys if k in d }

def filter_dict_list(l, keys):
    return [ filter_dict(d, keys) for d in l ]

But you can also combine both functions into only one:

def filter_dict_list(l, keys):
    return [ { k: d[k] for k in keys if k in d } for d in l ]

# Likewise, using the filter() function
def filter_dict_list(l, keys):
    return [ dict(filter(lambda item: item[0] in keys, d.items())) for d in l ]
by
selected by
Contributions licensed under CC0
...