How to match 2 items from list and list of dictionaries?

Question:

I have two objects: list of dictionaries:

object1 = [{'samplekey', 'samplevalue'}, {'samplekey1', 'samplevalue1'}, {'samplekey2', 'samplevalue2'},]

And a list of different objects:

object2 = [["samplekey", "samplevalue", { "connection": "Direct"}],["samplekey1", "samplevalue1",{ "connection": "Cross"}]]

My task if to find for each object1 proper match in object2 and get connection value. How to find them?

I’ve tried different variations of for loops and if statements but nothing works

Asked By: CodeDebagger

||

Answers:

You could convert the first 2 elements of each item in object2 to set, use len(o1) in case you need varying lengths:

object1 = [
    {'samplekey', 'samplevalue'},
    {'samplekey1', 'samplevalue1'},
    {'samplekey2', 'samplevalue2'},
    {'samplekey3', 'samplevalue3', 'samplevalue3'},
]
object2 = [["samplekey", "samplevalue", {
    "connection": "Direct"
}], ["samplekey1", "samplevalue1", {
    "connection": "Cross"
}], ["samplekey3", "samplevalue3", "samplevalue3", {
    "connection": "33333"
}]]

for o1 in object1:
    for o2 in object2:
        if set(o2[:(len(o1))]) == o1:
            print(o2[-1]['connection'])

Out:

Direct
Cross
Answered By: Maurice Meyer

You can use a nested for loop to find the matching objects and get the connection value. The outer loop would iterate through the elements of object1, and the inner loop would iterate through the elements of object2. For each element in object1, you can use an "if" statement to check if the "samplekey" value matches the first element of an element in object2. If a match is found, you can retrieve the connection value from the nested dictionary of the matching element in object2. Here’s an example of the code:

object1 = [{'samplekey': 'samplevalue'}, {'samplekey1': 'samplevalue1'}, {'samplekey2': 'samplevalue2'},]
object2 = [["samplekey", "samplevalue", { "connection": "Direct"}],["samplekey1", "samplevalue1",{ "connection": "Cross"}]]
for obj1 in object1:
    key = list(obj1.keys())[0]
    val = list(obj1.values())[0]
    for obj2 in object2:
        if key == obj2[0] and val == obj2[1] :
            connection = obj2[2]['connection']
            print(connection)

It’s worth noting that the problem formulation is a little bit ambiguous as the first object is a list of sets and not a list of dictionaries, but the above code should work regardless.

Answered By: saif amdouni
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.