2

I have two dictionaries, and I want to compare them and see what is different between the two. Where I am getting confused is the dict. Is there a name for this?

Everything is working fine, I just don't really understand why it works or what it is doing.

x = {"#04": 0, "#05": 0, "#07": 0, "#08": 1, "#09": 0, "#10": 0, "#11": 1, "#12": 1, "#14": 1, "#15": 1, "#17": 0, "#18": 1, "#19": 1, "#20": 1}

y = {"#04": 1, "#05": 0, "#07": 0, "#08": 1, "#09": 0, "#10": 0, "#11": 1, "#12": 1, "#14": 1, "#15": 0, "#17": 1, "#18": 1, "#19": 0, "#20": 1}

dict = {k: x[k] for k in x if y[k] != x[k]}

list = []

for k, v in dict.items()
  if v==0:
    difference = k + ' became ' + '0'
    list.append(difference)
  else:
    difference = k + ' became ' + '1'
    list.append(difference)

print(list)

It should print ['#04 became 0', '#15 became 1', '#17 became 0', '#19 became 1'] but I don't understand how the dict works to loop through the x and y dictionaries.

Life is complex
  • 15,374
  • 5
  • 29
  • 58
  • 3
    It is called "dictionary comprehension", look it up. Also don't use variable names such as `dict` and `list` as they will mask the built-in names. – Selcuk Mar 27 '19 at 01:30
  • 1
    `dict` is a built-in, you should not use it as a variable. – dcg Mar 27 '19 at 01:30
  • Possible duplicate of [Dictionary Comprehension in Python 3](https://stackoverflow.com/questions/20489609/dictionary-comprehension-in-python-3) – Sociopath Mar 27 '19 at 04:38

1 Answers1

1

The procedure implemented is comparing two dictionaries assuming that both have the same keys (potentially y could have more entries).

To make this comparison quick, and facilitate the next code block, they decided to generate a dictionary that only contains the keys that have different values.

To generate such dictionary, they use a "dictionary comprehension", which is very efficient.

Now, this construct:

d = {k: x[k] for k in x if y[k] != x[k]}

can be rewritten as:

d = {}
for k,v in x:          # for each key->value pairs in dictionary x
    if y[k] != x[k]:   # if the corresponding elements are different
        d[k] = x[k]    # store the key->value pair in the new dictionary

You could replace x[k] with v above.

sal
  • 3,515
  • 1
  • 10
  • 21