main_list = [“projecttype”, “emptype”, “Designation”]
main_list is to check the key exist in the dictionary or not
Primary Dict
sample_P = { "query": { "emptype": ["Manager", "AM"], "Designation": ["Developer"], "from": ["0"], "q": [""], "size": ["4"] } }
Secondary Dict
sample_S = { "query": { "emptype": ["Manager"], "Designation": ["Developer"], "from": ["0"], "q": [""], "size": ["4"] } }
- 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
current_dict = {} for key, items in sample_P["query"].items(): if key in main_list: for key, items in sample_S["query"].items(): #if values changes for the key #create a new dictionary and add to last part of dict
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.
current_dict = {} changed_dict = {} for item in main_list: if sample_P.get("query").get(item) and sample_S.get("query").get(item): if sample_P.get("query").get(item) != sample_S.get("query").get(item): changed_dict[item] = sample_S.get("query").get(item) else: current_dict[item] = sample_S.get("query").get(item) else: print("key {} not found ".format(item)) current_dict.update(changed_dict)