简体   繁体   中英

How to compare two dictionaries in python with list, string and integer?

results = {}
expectedResults = {}

results['a'] = 3
results['b'] = [1, 2]
results['c'] = '2A 04 73 74'

expectedResults['a'] = 3
expectedResults['b'] = [1, 2]
expectedResults['c'] = '2A 04 73 74'

compare = dict(set(results.items())-set(expectedResults.items()))
print(str(compare))

I get the following error. TypeError: list objects are unhashable

I am using the following compare, so that the unmatched key: value pair (if any) shows in the print statement.

compare = dict(set(results.items())-set(expectedResults.items()))

If lists are the only unhashable type in your dictionary, you could create dictionaries to use for comparison that convert lists to tuples:

results = {'a': 3, 'b': [1, 2], 'c': 'this is unmatched'}
expected_results = {'a': 3, 'b': [1, 2], 'c': 'blablabla'}

a_items = {k: tuple(v) if isinstance(v, list) else v for k, v in results.items()}
b_items = {k: tuple(v) if isinstance(v, list) else v for k, v in expected_results.items()}

compare = dict(set(a_items.items())-set(b_items.items()))
print(compare)

Output:

{'c': 'this is unmatched'}

you could utilize difflib to find difference.

  1. convert dict to string
  2. check the difference between string

     import difflib import pprint results = {} expectedResults = {} results['a'] = 3 results['b'] = [1, 2] results['c'] = '2A 04 73 74' expectedResults['a'] = 3 expectedResults['b'] = [1, 2] expectedResults['c'] = 'test' print '\\n'.join(difflib.ndiff(pprint.pformat(results).splitlines(), pprint.pformat(expectedResults).splitlines())) 

    output:

     - {'a': 3, 'b': [1, 2], 'c': '2A 04 73 74'} ? ^^^^^^^^^^^ + {'a': 3, 'b': [1, 2], 'c': 'test'} ? 

You are getting this error because when you call results.items(), it returns a list which is not a hashable.

A simple way to make your code work would be to iterate through each dict item and check for it's equality

for i in results:
if(results[i] !=  expectedResults[i]):
    print('different key : value pair')
    print('key : ' + i)
    print('Value in results : ' + str(results[i]))
    print('Value in expectedResults : ' + str(expectedResults[i]))

Your can't get a solution as simple as this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM