簡體   English   中英

從 Python 中的嵌套字典打印多個特定鍵

[英]Printing multiple specific keys from a nested dictionary in Python

好的,這只是一個大程序的一部分。

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"},
   ...:                 },
   ...:             },
   ...:         }
   ...:     ]
   ...: }

我可以像這樣在嵌套字典 Sns 中打印單個鍵值:

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

但是如何打印多個鍵值呢?。

以下方法失敗。

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

你在列表中得到你的值:

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

在字典中:

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

您也可以像這樣解壓它們:

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

在不同的行上:

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

在一行上但存儲為數組:

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

您可以運行一個 for 循環,遍歷要在字典中打印多個嵌入元素的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM