简体   繁体   English

从 Python 中的嵌套字典打印多个特定键

[英]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:我可以像这样在嵌套字典 Sns 中打印单个键值:

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.您可以运行一个 for 循环,遍历要在字典中打印多个嵌入元素的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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