简体   繁体   中英

Sort a dictionary by multiple keys that represent the same value

I have a list of dictionaries, in each dictionary is a date ( datetime.datetime objects), but in some cases it is associated with the key "created_at" and in other cases "notification_timestamp" .

data = [{'foo':'bar', 'created_at':'00:15:20 04/05/2019'},{'foo2':'bar2', 'notification_timestamp':'00:35:20 04/05/2019'}]

I know that I could just rename the keys but I need an efficient/scalable solution to ordering this list by these keys.

I have tried data = data.sort(key=operator.itemgetter("created_at", "notification_timestamp"), reverse=True) but it throws the following error:

Exception Type: KeyError at /v1/my_script
Exception Value: 'notification_timestamp'

presumably because not all the dictionaries have this key.

I am certain of the data types of my variables, the output of this script

for d in data:
    if d.get("created_at", False):         
        print("CREATED AT TYPE: ", type(d.get("created_at")))
    if d.get("notification_timestamp", False):
        print("notification_timestamp TYPE: ", type(d.get("notification_timestamp")))

is

CREATED AT TYPE:  <class 'datetime.datetime'>
notification_timestamp TYPE:  <class 'datetime.datetime'>

All help is appreciated

感谢@Rakesh向我展示了在这种情况下使用x.get()的可能性,我找到了一个解决方案:

data.sort(key=lambda x: x.get("created_at", x.get("notification_timestamp", None)), reverse=True)

Try using dict.get

Ex:

data = [{'foo':'bar', 'created_at':'00:15:20 04/05/2019'},{'foo2':'bar2', 'notification_timestamp':'00:35:20 04/05/2019'}]
data.sort(key=lambda x: x.get("created_at", x.get("notification_timestamp")))  #Thanks AbdulNiyasPM & h4z3
print(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM