main_list = [“projecttype”, “emptype”, “Designation”]
main_list is to check the key exist in the dictionary or not
Primary Dict
JavaScript
x
10
10
1
sample_P = {
2
"query": {
3
"emptype": ["Manager", "AM"],
4
"Designation": ["Developer"],
5
"from": ["0"],
6
"q": [""],
7
"size": ["4"]
8
}
9
}
10
Secondary Dict
JavaScript
1
10
10
1
sample_S = {
2
"query": {
3
"emptype": ["Manager"],
4
"Designation": ["Developer"],
5
"from": ["0"],
6
"q": [""],
7
"size": ["4"]
8
}
9
}
10
- Check the sample_P exist in the main_list
- Check the sample_S exist in the main_list
- Check if any key changes is there?
- If changes then changed key will goes to last part of the dictionary
- Only one key will change at one time
“emptype” key has changed in the secondary, if any change in the key it will goes to last
{"Designation":["Developer"], "emptype":["Manager"] }
Basically I need to check key’s in the both dictionaries if any changes in the dictionary key then it will goes to last
Code is below
JavaScript
1
6
1
current_dict = {}
2
for key, items in sample_P["query"].items():
3
if key in main_list:
4
for key, items in sample_S["query"].items():
5
#if values changes for the key #create a new dictionary and add to last part of dict
6
Advertisement
Answer
You can iterate over the list of key if that is smaller and access the value of key using get. I have stored the changes result to a new dictionary.
JavaScript
1
12
12
1
current_dict = {}
2
changed_dict = {}
3
for item in main_list:
4
if sample_P.get("query").get(item) and sample_S.get("query").get(item):
5
if sample_P.get("query").get(item) != sample_S.get("query").get(item):
6
changed_dict[item] = sample_S.get("query").get(item)
7
else:
8
current_dict[item] = sample_S.get("query").get(item)
9
else:
10
print("key {} not found ".format(item))
11
current_dict.update(changed_dict)
12