0

A list and dictionary is below

main_list = ["projecttype","emptype","Designation"]
sample = {"query": {
      "emptype":["Manager"],"projecttype":["temp"],
    "from": [
      "0"
    ],
    "q": [
      ""
    ],
    "size": [
      "4"
    ]
  }}
  1. How to find from the main_list which key is last "entered key" in sample dictionary

  2. How to find from the main_list which key is first "entered key" in sample dictionary

In this particular scenario

  1. "projecttype" is my output for last entered key which matches
  2. emptype is my output for first entered key which matches
  • Perhaps this is splitting hairs, but technically `query` is the only key in your `sample` dict. Is there a reason your example needs a dict in a dict, and each of the inner dict's values is also wrapped in a single-value list? – CrazyChucky Nov 26 '20 at 05:36
  • @CrazyChucky my sample dict is very big i just extract the `query` from that –  Nov 26 '20 at 05:38
  • 1
    Dictionaries only recently added the ability to order by insertion order. You'll need to be using a very recent version of Python, and use `dict.items()` with slicing. – Mark Ransom Nov 26 '20 at 05:38
  • 1
    Maybe this could help: https://stackoverflow.com/a/43491315/10011503 – s.k Nov 26 '20 at 05:40
  • To follow up on Mark Ransom's comment, dicts have been de facto ordered since 3.5, and are only *guaranteed* to be ordered since 3.7. If you're using an older version, you could use OrderedDict. – CrazyChucky Nov 26 '20 at 05:54

2 Answers2

1

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)
mazore
  • 984
  • 5
  • 11
  • 1
    instead of `for key, value in sample['query'].items():`, you could simplify that slightly to `for key in sample['query'].keys():`. No sense unpacking the values if you don't use them. – CrazyChucky Nov 26 '20 at 05:48
0

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.

Erick Rodriguez
  • 208
  • 1
  • 3
  • 9