Search code examples
pythondictionaryfor-loopiterationtheory

Insight Into A Loop


Hey I got this from StackOverflow, It counts the common values between two dictionaries but I'm hoping someone can take the time to break down the process as it's not explained in the answer section of the topic.

I think I get that;

dictionary1[key] for key in dictionary1 if key in dictionary2 and dictionary1[key] == dictionary2[key]

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(shared_items)

Does it only match where the key, value in both dictionaries match? also, why the k: at the start?

Anyway I know it's a random question but this type of iteration is really neat especially when you change the == to <= and >= it can be really useful and hopefully someone can take the time to break it down so I can wrap my head around it. Thanks.


Solution

  • This is known as 'dict comprehension', similar to 'list comprehension'. Basically, the line

    shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
    

    is equivalent to:

    shared_items = {}
    for k in x:
        if k in y and x[k] == y[k]:
            shared_items[k] = x[k]