简体   繁体   中英

Printing multiple specific keys from a nested dictionary in Python

Ok, this is just a portion of a large program.

In [1]: event = {
   ...:     "Records": [
   ...:         {
   ...:             "EventSource": "aws:sns",
   ...:             "EventVersion": "1.0",
   ...:             "EventSubscriptionArn": "arn:aws:sns:eu-XXX-1:XXXXX:aws_XXX",
   ...:             "Sns": {
   ...:                 "Type": "Notification",
   ...:                 "MessageId": "95XXXXX-eXXX-5XXX-9XXX-4cXXXXXXX",
   ...:                 "TopicArn": "arn:aws:sns:us-XXX-1:XXXXXXX:EXXXXXTXXX",
   ...:                 "Subject": "example subject",
   ...:                 "Message": "example message",
   ...:                 "Timestamp": "1970-01-01T00:00:00.000Z",
   ...:                 "SignatureVersion": "1",
   ...:                 "Signature": "EXAMPLE",
   ...:                 "SigningCertUrl": "EXAMPLE",
   ...:                 "UnsubscribeUrl": "EXAMPLE",
   ...:                 "MessageAttributes": {
   ...:                     "Test": {"Type": "String", "Value": "TestString"},
   ...:                     "TestBinary": {"Type": "Binary", "Value": "TestBinary"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }

I am able to print single key value inside the nested dictionary Sns like this:

In [29]: event["Records"][0]["Sns"]["Subject"]
Out[29]: 'example subject'

But how to print multiple key values of it?.

The following way fails.

In [38]: event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [38], in <module>
----> 1 event["Records"][0]["Sns"](["Timestamp"], ["Subject"], ["Message"])

TypeError: 'dict' object is not callable

You get your values in a list:

print([event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]])

In a dict:

print({k:event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]})

You can also unpack them like:

a, b, c = [event["Records"][0]["Sns"][k] for k in ["Timestamp", "Subject", "Message"]]

On separate lines:

for x in ("Timestamp", "Subject", "Message"):
    print(event["Records"][0]["Sns"][x])

On one line but stored as an array:

a = []
for x in ("Timestamp", "Subject", "Message"):
    a.append(event["Records"][0]["Sns"][x])
print(a)

You could run a for loop, looping through the elements you want to print multiple imbedded elements in the dictionary.

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