0

I am trying to pass the dictionary path as a variable into a function. That path variable points to the sort key for sort():

time_ordered_versions = sorted(versions, key=lambda i: i[sort_key], reverse=True)

I am passing the sort key as follows according to this solution:

sort_key=('ResponseMetadata','HTTPHeaders','date')

However this approach is throwing an KeyError:

KeyError: ('ResponseMetadata', 'HTTPHeaders', 'date')

This is the correct path, because if I manually put in

 i['ResponseMetadata']['HTTPHeaders']['date']

everything works as expected.

Is there a way to pass path as variable here?

kravb
  • 417
  • 4
  • 16

1 Answers1

0

In the solution you link the dictionary is changed to be a single level. As you do not specify if you want to do that, will assume you want to keep the dictionary structure unchanged. A solution is (I have created a simplified versions and sort_key, but the code will work on your case as well):

versions = [{'level1': {'level2':2}}, {'level1': {'level2':3}}]
sort_key = ('level1','level2')

def get_key(data, path):
    for i in path:
        data = data[i]
    return data

time_ordered_versions = sorted(versions, key=lambda i: get_key(i,sort_key), reverse=True)

print(time_ordered_versions)

The get_key functions takes the path array (sort_keys) and the dictionary and returns the key by traversing the path one by one. You can do further checks in get_key (if for example not all elements have the path)

vladmihaisima
  • 2,119
  • 16
  • 20