Reputation:
A list and dictionary is below
main_list = ["projecttype","emptype","Designation"]
sample = {"query": {
"emptype":["Manager"],"projecttype":["temp"],
"from": [
"0"
],
"q": [
""
],
"size": [
"4"
]
}}
How to find from the main_list which key is last
"entered key" in sample dictionary
How to find from the main_list which key is first
"entered key" in sample dictionary
In this particular scenario
"projecttype"
is my output for last entered key which matchesemptype
is my output for first entered key which matchesUpvotes: 0
Views: 66
Reputation: 198
You could do this in a cuple of lines and have the order of all the elements that are contained in your main_list
as follow:
sample_query_keys = list(sample['query'].keys())
result = {sample_query_keys.index(main_key):main_key for main_key in main_list if main_key in sample_query_keys}
Then you can get the first and last item as follow:
print(result[0], result[len(result)-1])
Keep in mind that this will only work if the dictionary is ordered. That is only possible in Python 3.7 onwards. For previous versions, you would need to use OrderedDict.
Upvotes: 0
Reputation: 1024
You can iterate through it and test if the keys are in your main_list
. Save every key that is in main_list
and after the for loop you will have the last entered key.
main_list = ["projecttype","emptype","Designation"]
sample = {
"query": {
"emptype": ["Manager"],
"projecttype": ["temp"],
"from": ["0"],
"q": [""],
"size": ["4"]
}
}
first = None
last = None
for key, value in sample['query'].items():
if key in main_list:
if first is None:
first = key
last = key
print('First:', first)
print('Last:', last)
Upvotes: 1