简体   繁体   中英

Python Dict Key Error. How do I loop through nested dict and check for a key

I have the following nested dict below which I'm trying to loop through. Well, not necessarily loop through but I just want to check that the label has a value "EDD". If it does then I want to trigger some other action.

My problem is that I keep getting an error for labels key error.

Please how do I do this.

message.data = {
          "messages": [{
            "to": "wa-id",
            "from": "another-wa-id",
            "type": "text",
            "_vnd": {
              "v1": {
                "direction": "outbound",
                "in_reply_to": "an-earlier-inbound-external-id",
                "author": {
                  "name": "the name of the author",
                  "type": "SYSTEM | OPERATOR",
                },
                "labels": [{
                  "uuid": "the-uuid",
                  "value": "EDD"
                }]
              }
            }
          }, ]
        }

My code looks like so:

 whatsapp_contact_id = message.data
    print(whatsapp_contact_id.keys())
    list_data = whatsapp_contact_id["messages"]
    print(list_data)
    for dictionary_data in list_data:
        print(dictionary_data)
    dictionary_keys = dictionary_data.items()
    print(dictionary_keys)
    """
    EDD_label = dictionary_data["labels"]
    """
    EDD_label = dictionary_data.get('labels', 'could not find')
    print("The label is below")
    print(EDD_label) 

Assuming the structure stays constant, what you want is:

whatsapp_contact_id = message.data
list_data = whatsapp_contact_id.get("messages")
for dictionary_data in list_data:
    dictionary_data_2 = dictionary_data.get("_vnd").get("v1")
    labels_data = dictionary_data_2.get("labels")
    print(labels_data)
    for EDD in labels_data:
        EDD_string = EDD.get("value", "EDD label not present")
        print(EDD_string)

Also, you appear to have triple-pasted your code.

Edited to include final code from OP

Thanks everyone especially @tennoshi.

This works:

whatsapp_contact_id = message.data
    list_data = whatsapp_contact_id.get("messages")
    for dictionary_data in list_data:
        dictionary_data_2 = dictionary_data.get("_vnd").get("v1")
        labels_data = dictionary_data_2.get("labels")
        print(labels_data)
        for EDD in labels_data:
            EDD_string = EDD.get("value", "EDD label not present")
            print(EDD_string)```

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