[技术经验][Python] 比较两个字典 dictionaries 的 value
1. Background
Language: Python version 3.7
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. from W3schools
Two dictionaries:
- same key number,
- different key name,
- different values.
dictionary_1 = {
"key_1": "val_1",
"key_2": "val_2",
"key_3": "val_3",
}
dictionary_2 = {
"key_11": "val_1",
"key_21": "val_21",
"key_31": "null",
}
Expectation:
(1) compare two dictionaries by key in sequence,
(2) if the value is different, then copy the key:value pairs into new dictionary.
2. Technical solution
2.1 flow chart
graph TD
A(start) --> B[put dict_2 into one iterator]
B --> C[loop dict_1 by its key]
C --> D{end of loop?}
D --> |Yes| Da[return dict_result]
Da --> E(End)
D --> |No| Db[get value_1 from dict_1 by key_1]
Db --> F[get Key_2 from iterator; move to next one in the itrator]
F --> G[get Value_2 via Key2]
G --> H{Value1 != value_2}
H --> |True| Ia[update key_1:value_2 in dict_result]
H --> |False| Ib[do nothing]
Ia --> C
Ib --> C
2.2 Implementation
#####################################################################
# Description:
# (1) identify different value between dictionary_Ref and dictionary_Comp;
# (2) copy the different value and its key;
# (3) add the different value and its key into new dictionary_result.
# Arguments:
# (1) dict_Ref: dictionary, which is taken as Ref.
# (2) dict_Comp: dictionary, which is to compare. same length as dict_Ref.
#####################################################################
def compare_2_dictionaries(dict_Ref, dict_comp):
dict_result = {}
myiter = iter(dictionary_2)
cnt_of_myiter = len(dictionary_2)
for key_in_dict_1 in dictionary_1.keys():
value_of_key_in_dict_1 = dictionary_1[key_in_dict_1]
key_in_dict_2 = next(myiter)
value_of_key_in_dict_2 = dictionary_2[key_in_dict_2]
if value_of_key_in_dict_1 != value_of_key_in_dict_2:
dict_result.update({key_in_dict_1:value_of_key_in_dict_2})
else:
pass
return dict_result
call above function:
compare_2_dictionaries(dictionary_1, dictionary_2)
output of the function:
{'key_2': 'val_21', 'key_3': 'null'}
3 Reference
3.1 dictionary
Ref_1: https://www.w3school.com.cn/python/python_dictionaries.asp
Ref_2: Https://docs.python.org/3/tutorial/datastructures.html#dictionaries
3.2 Iterator
Ref_1: https://www.w3school.com.cn/python/python_iterators.asp
Ref_2: https://docs.python.org/3/tutorial/classes.html#iterators
浙公网安备 33010602011771号