chomes
chomes

Reputation: 79

Alternatives to for loops traversing 3 lists of dicts

So I've seen a few posts which I've tried to look at but my use case is a bit different. I have 3 lists which have multiple dicts in them and to get information from them I sometimes have to go through 2 or sometimes all 3.

To do this currently I do:

item_dict = {}
excludes = ["excluded devices"]
confirm = "value"
for item in first_list_dict:
    for second_item in second_list_dict:
            for key, value in item.items():
                if value == confirm and item["key"] == "value" and item["key2"] not in excludes and item["key3"] == second_item["key"]:
                     if second_item["key"] not in item_dict:
                         item_dict[second_item["key"]] = [{item["key"]: {"info": item["key"], "mac_address": item["key"]}}]
                     else:
                         item_dict[second_item["key"]].append({item["key"]: {"info": item["key"], "mac_address": item["key"]}})

This looks like...a hot mess so let me explain what I'm doing.

2 lists of dictionaries with some separated data but can be linked together with a key they both have in each dictionary.

The for loop is essentially used to confirm that certain conditions exist in a separate list, a external value and keys in dictionaries match, add items to a dictionary.

What I'd like to know is, if there are alternatives to using this nested for loop and if it could be explained how it works I would be extremely grateful. Feel free to ask any questions you want me to answer so I can explain this more.

Upvotes: 0

Views: 69

Answers (1)

Alex Hall
Alex Hall

Reputation: 36043

Here's a bit of refactoring to get started:

from collections import defaultdict

item_dict = defaultdict(list)
excludes = ["excluded devices"]
confirm = "value"
for item in first_list_dict:
    for value in item.values():
        val1 = item["key"]
        if not (val1 == "value" and value == confirm and item["key2"] not in excludes):
            continue
        for second_item in second_list_dict:
            val2 = second_item["key"]
            if item["key3"] == val2:
                item_dict[val2].append({val1: {"info": val1, "mac_address": val1}})

Upvotes: 2

Related Questions