Compare 2 dictionaries in python

Compare 2 dictionaries in python

By : Ed Maste
Date : November 19 2020, 07:01 PM
around this issue Python 2:
Assuming by 'entry' you mean 'key', a solution is to use set difference on the dictionary keys with something likee set(dict1.keys()) - set(dict2.keys())
code :
>>> a = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> b = {'a': 1, 'c': 3}
>>> a.keys()
['a', 'c', 'b', 'd']
>>> b.keys()
['a', 'c']
>>> set(a.keys())-set(b.keys())
set(['b', 'd'])
dict1.keys() - dict2.keys()
dict1.keys() ^ dict2.keys()

Share : facebook icon twitter icon
compare two dictionaries in python

compare two dictionaries in python

By : user3142580
Date : March 29 2020, 07:55 AM
hop of those help? By recursion function for nested dictionary.
Get common keys from both dictionary by keys() and set operation. Iterate common keys by for loop. Check type of value of key is dict or not. If value type is dict then call same function and pass values dictionary as arguments. and add result as key into modified dictionary. If value type is not dict then add into modified dictionary.
code :
dict1 = { 
        'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 
        'medic2' : {'date' : '02/03/2015', 'no' : '456' },
        'testkey1': 'testvalue1',
        'testkey2': 'testvalue2',
        'testkey3':{ "level2_1":"value2_1", 
                        "level3_1": "value3_1_change", 
                        "level3_2": "value3_2", 

dict2 = { 
        'medic1' : {'date' : '02/02/2015', 'no' : '456' }, 
        'medic2' : {'date' : '02/03/2015', 'no' : '456' },
        'testkey1': 'testvalue1',
        'testkey2': 'testvalue22',
        'testkey3':{ "level2_1":"value2_1", 
                                "level3_1": "value3_1", 
                                "level3_2": "value3_2", 


import copy

def compareDict(dict1, dict2):

    d1_keys = dict1.keys()
    d2_keys = dict2.keys()
    intersect_keys = set(d1_keys).intersection(set(d2_keys))
    modified = {}
    for i in intersect_keys:
        if dict1[i] != dict2[i] : 
            if isinstance(dict1[i], dict) and isinstance(dict1[i], dict):
                modified[i]=compareDict(dict1[i], dict2[i])
                modified.update({i : (dict1[i], dict2[i])})

    return copy.deepcopy(modified)

modified = compareDict(dict1, dict2)
import pprint
vivek@vivek:~/Desktop/stackoverflow$ python 5.py 
{'medic1': {'no': ('123', '456')},
 'testkey2': ('testvalue2', 'testvalue22'),
 'testkey3': {'level2_2': {'level3_1': ('value3_1_change', 'value3_1')}}}
how to compare two dictionaries in python

how to compare two dictionaries in python

By : user1928810
Date : March 29 2020, 07:55 AM
Does that help Here's a simplified version of your problem. You can group your AwardsDict "value" dictionaries by NSN and then compare and match.
code :
RFQDict = {
    'a': {'Add_method': 'D1', 'NSN': '9905'},
    'b': {'Add_method': 'D2', 'NSN': '9906'},
    'c': {'Add_method': 'D3', 'NSN': '9907'},
    'd': {'Add_method': 'D4', 'NSN': '9908'}
AwardsDict = {
    'W21': {'Awarddate': '08-13-2007', 'Awardid': '1', 'NSN': '9906'},
    'W22': {'Awarddate': '08-14-2007', 'Awardid': '2', 'NSN': '9905'},
    'W23': {'Awarddate': '08-15-2007', 'Awardid': '3', 'NSN': '9908'},
    'W24': {'Awarddate': '08-16-2007', 'Awardid': '4', 'NSN': '9907'},

# First create a new dictionary with "NSN" as keys and awards as matches 
nsn_awards = {v['NSN']: v for v in AwardsDict.values()}

# go through all values of RFQDict and find a match by
# looking up the its NSN in the nsn_awards_dict
matches = [(rfq, nsn_awards[rfq['NSN']]) for rfq in RFQDict.values()]

[({'NSN': '9908', 'Add_method': 'D4'}, {'NSN': '9908', 'Awardid': '3', 'Awarddate': '08-15-2007'}), ({'NSN': '9907', 'Add_method': 'D3'}, {'NSN': '9907', 'Awardid': '4
', 'Awarddate': '08-16-2007'}), ({'NSN': '9906', 'Add_method': 'D2'}, {'NSN': '9906', 'Awardid': '1', 'Awarddate': '08-13-2007'}), ({'NSN': '9905', 'Add_method': 'D1'}
, {'NSN': '9905', 'Awardid': '2', 'Awarddate': '08-14-2007'})]
matches = []
for rfq in RFQDict.values():
    if rfq['NSN'] in nsn_awards: # only append if there's a match
        nsn = rfq['NSN']
        matches.append((rfq, nsn_awards[nsn]))
Compare dictionaries using python

Compare dictionaries using python

By : Ida Jaa
Date : March 29 2020, 07:55 AM
wish helps you Use dictionary view objects and use set operations:
Python: Compare values from 2 dictionaries with the same key

Python: Compare values from 2 dictionaries with the same key

Date : March 29 2020, 07:55 AM
this one helps. If what you want is to see how many of any given car can be created without actually affecting the contents of Materials, you could write your method like so:
Compare dictionaries in python

Compare dictionaries in python

By : h5s5
Date : March 29 2020, 07:55 AM
may help you . Well, for one, you get KeyError because you try to look up keys which don't exist in both dicionaries.
It sounds to me like you want to compute an intersection of two dictionaries. In such case, it's enough to:
code :
>>> a = dict(a=1, b=2, c=3)
>>> b = dict(b=2, c=3, d=4)
>>> dict(a.items() & b.items())
{'c': 3, 'b': 2}
Related Posts Related Posts :
  • read a binary file (python)
  • Number Sequence in MySQL
  • Unit testing in python?
  • s/mime v3 with M2Crypto
  • Using wget via Python
  • Running a python script in background from a CGI
  • Edit Distance in Python
  • how to read url data
  • A RAM error of big array
  • Python: For loop problem
  • How do I create a list with 256 elements?
  • RAW Image processing in Python
  • access django session from a decorator
  • Multi-Threaded data insertion in MySQL using python
  • Making all variables accessible to namespace
  • What are the differences among sqlite3 from python2.5, pysqlite and apsw
  • Detect marker with opencv and python
  • Python ctypes and dynamic linking
  • Downloading a directory tree with ftplib
  • ImportError: No Module named simplejson
  • Pre-generating GUIDs for use in python?
  • `ipython` tab autocomplete does not work on imported module
  • Matching blank entries in django queryset for optional field with corresponding ones in a required field
  • Control VLC from Python in Windows
  • Return unicode string from python via ajax
  • Dynamically customize django admin columns?
  • Any way to add tabbed forms in django administration site?
  • Python / SQLite - database locked despite large timeouts
  • Encoding in XML declaration python
  • deletion of folders
  • Python Mindstorms RCX
  • Regex to split on successions of newline characters
  • Unicode filename to python subprocess.call()
  • Removing non-breaking spaces from strings using Python
  • Is there a way to backup everything in an app-engine blobstore?
  • Process a set of files from a source directory to a destination directory in Python
  • How to know if optparse option was passed in the command line or as a default
  • Rewriting a for loop in pure NumPy to decrease execution time
  • Comparing a time delta in python
  • Find next lower item in a sorted list
  • MySQLdb not INSERTING, _mysql does fine
  • Scipy Negative Distance? What?
  • What are the common patterns in web programming?
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk