jeudi 8 octobre 2020

How to improve my if else logic while appending from list of dicts?

I have a list of dicts x with some metadata and I may/may not have another list of just strings y without metadata which is a subset of the previous list.

I want to iterate over x and append the string with some of the metadata to another list z. If I have y, I want to just add metadata of the strings in y from x to z.

I have this solution so far and I think this can be improved, if not I will remove the question.

x = [
    {"a": "valuea0", "b": "valueb0"},
    {"a": "valuea1", "b": "valueb1"},
    {"a": "valuea2", "b": "valueb2"},
]
y = ["valueb0", "valueb1"]
z = []

def so_question(x, **kwargs):
    test_kwarg = kwargs.get("test_kwarg", None)

    for item in x:
        test_string = item["b"]
        if test_kwarg:
            if test_string in test_kwarg:
                z.append(
                    {
                        "p": item["a"],
                        "q": item["b"],
                    }
                )
        else:
            z.append(
                {
                    "p": item["a"],
                    "q": item["b"],
                }
            )
    return z

print(so_question(x, test_kwarg=y))

Expected output:

z = [
    {"a": "valuea0", "b": "valueb0"},
    {"a": "valuea1", "b": "valueb1"},
]

How can I improve this if/else logic since I am doing the same thing in both if and else?

Aucun commentaire:

Enregistrer un commentaire