# Compare two dictionarys and return a new dictionary # containing only key value pairs where the key and the value # are the same in both dictionarys # Resources Used # http://stackoverflow.com/questions/13714982/comparing-two-dictionaries-key-values-and-returning-the-value-if-match # http://stackoverflow.com/questions/3786881/what-is-a-method-in-python # http://learnpythonthehardway.org/book/ex39.html # http://learnpythonthehardway.org/book/ex21.html # Create a class to put the compare code in so it can be # reused easily elsewhere. class DictionaryCompare: @staticmethod def get_common_key_value_pairs(first_dictionary, second_dictionary): result_dictionary = {} for key in first_dictionary.keys(): if key in second_dictionary.keys(): if first_dictionary[key] == second_dictionary[key]: result_dictionary[key] = first_dictionary[key] return result_dictionary # Setup the input dicts first_dictionary = {'bean': 1, 'egg': 2, 'moonpie': 3, 'lamb': 4} second_dictionary = {'bean': 1, 'egg': 3, 'baked_bean': 3, 'lamb': 4} # Call the unbound method on the DictionaryCompare class results = DictionaryCompare.get_common_key_value_pairs(first_dictionary, second_dictionary) # Print out the results for key, value in results.items(): print(key) print(value)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question