Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

python 3.x - use tuple as dictionary path for sorting

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...