【问题标题】:Python3 check if exact string match in the event dictionaryPython3 检查事件字典中的字符串是否完全匹配
【发布时间】:2022-11-22 23:05:07
【问题描述】:

我有以下事件主体(字典)进入 lambda 函数,我做了类似下面的事情:

{
  "test-report": {
    "document-uri": "http://example.com/index.html",
    "original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-reports"
  }
}

if 'test-report' in event['body']:
    try:
        do something here

我的问题是我想在字典的第一个对象中检查test-report。如果不匹配,我不希望该函数执行任何操作。但是,如您所见,**test-report**s 也出现在 original-policy 值下,我不想在我的 if 语句中考虑这些值。

更新:

这是完整的请求上下文。

{
   "requestContext":{
      "elb":{
         "targetGroupArn":"arn:aws:elasticloadbalancing:us-east-2:xxxxxx:targetgroup/lambda-xxxxxxx/xxxxxxx"
      }
   },
   "httpMethod":"POST",
   "path":"/lambda",
   "queryStringParameters":{
      "query":"1234ABCD"
   },
   "headers":{
      "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
      "accept-encoding":"gzip",
      "accept-language":"en-US,en;q=0.9",
      "connection":"keep-alive",
      "host":"alb.com",
      "upgrade-insecure-requests":"1",
      "user-agent":"test",
      "x-amzn-trace-id":"Root=1-xxxxxxxxxxxx",
      "x-forwarded-for":"x.x.x.x",
      "x-forwarded-port":"80",
      "x-forwarded-proto":"http",
      "x-imforwards":"20"
   },
   "body":{
      "test-report": {
        "document-uri": "http://example.com/index.html",
        "original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-reports"
      }
   },
   "isBase64Encoded":false
}

【问题讨论】:

  • 要重现该问题,示例代码缺少 body。请更新响应事件
  • 字典的 in 运算符只是测试是否有匹配的键,它不会更深入。我没有看到问题。
  • 'test-report' in event['body']检查event['body']是否有键'test-report'(假设event['body']是一个字典)
  • 当您在字典上使用 in 时,它只会检查钥匙;它不检查价值观.所以这应该完全按照你的意愿工作。 (但是,大概你遇到了某种问题,否则你不会发布这个问题,所以看来你需要解释更多......)
  • 感谢大家。是的,正文是一本字典。我更新了问题。

标签: python python-3.x lambda


【解决方案1】:

好吧,我假设,第一个对象是指字典中的键,因为它们没有排序。 如果是这样,请尝试:

  if 'test-report' in event['body'].keys():
  try:
do something here

【讨论】:

  • 这相当于 OP 的代码
  • 如果 event['body'] 是字典,则默认情况下将其视为迭代器仅检查键,因此这等同于问题中提供的代码。如果你想在 Python 中使用键/值对,你必须使用 dict.items()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
相关资源
最近更新 更多