How to compare 2 Ordered Dictionaries and create a new Ordered one with differences? (Python 3.7)

Question:

I’m struggling on how to generate a "Differences" Ordered-Dictionary containing the Different and also New values appearing on a "Modified" Ordered-Dictionary after comparing with a "Reference" Ordered-Dictionary.

EXAMPLE:

#python

from collections import OrderedDict

ref_d = OrderedDict() # REFERENCE Ordered Dictionary
mod_d = OrderedDict() # MODIFIED Ordered Dictionary
dif_d = OrderedDict() # DIFFERENCES Ordered Dictionary (what I'm looking for)

# This is my REFERENCE ordered dictionary with default values

ref_d = {
    'shape': 'square',
    'color': 'white',
    'posxy': '0,0',
    'scale': 'small',
    'rotxy': '0,0',
    'modif': 'no',
    'autom': 'no',
    'lumin': 'min',
    'backg': 'none',
    'outpu': 'no'
}

# This is my MODIFIED ordered dictionary, with some different values, and even some NEW key/value pairs

mod_d = {
    'shape': 'square',
    'color': 'red', # Different <-
    'posxy': '0,0',
    'scale': 'small',
    'rotxy': '0.5,0.5', # Different <-
    'modif': 'no',
    'autom': 'no',
    'varia': 'true', # NEW <-
    'lumin': 'max',
    'backg': 'none',
    'outpu': 'yes', # Different <-
    'specm': 'true' # NEW <-
}

# THIS IS WHAT I NEED: a "DIFFERENCES ordered dictionary", where different values and NEW key/values are added in same order

dif_d = {
    'color': 'red', # Different <-
    'rotxy': '0.5,0.5', # Different <-
    'varia': 'true', # NEW <-
    'outpu': 'yes', # Different <-
    'specm': 'true', # NEW <-
}

Using:

set0 = set(ref_d.items())
set1 = set(mod_d.items())
dif_d = (set1 - set0)

I get a valid result, except that it’s completely UNORDERED 🙁

I suppose it could be something like this (using a dirt non-valid code):

for key, value in mod_d.items():
    if key, value != or not in ref_d: # Consider this as 'pseudo-code', it obviously fails...
        dif_d.update({key: value})

But I constantly get an invalid code error…
Any help will be welcome!
THANKS!

Asked By: Cristobal Vila

||

Answers:

You cannot make two comparisons at the same time. You need two separate checks:

for key, value in mod_d.items():
    if key not in ref_d:
        dif_d.update({key: value})
    else:
        if value != ref_d[key]:
            dif_d.update({key: value})
Answered By: milchmannverleih

copied you code and worked for me:

$ python test.py
{('outpu', 'yes'), ('color', 'red'), ('specm', 'true'), ('lumin', 'max'), ('rotxy', '0.5,0.5'), ('varia', 'true')}

the only major difference is that you forgot the , chararcters after each key,value in your dictionaries.
Python needs that.
Example:

dictionary = 
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}
Answered By: Remzi