【问题标题】:Why code not working correctly for printing having { in python为什么代码在 python 中无法正常打印 {
【发布时间】:2020-07-14 14:53:22
【问题描述】:

我在下面有一本字典:

event = {
    "body-json": {},
    "params": {
        "path": {
            "matchphrase": "term"
        },
        "querystring": {
            "dataproduct.keyword": "health"
        },
        "header": {
            "Accept": "application/json"
        }
    },
    "resource-path": "/{matchphrase}"
}

我想访问上面的event 字典键和值并按如下方式构建一个新字典:

{"query": {"term" : {"dataproduct.keyword": "health"}}}

这是我尝试过的代码:

a = event['params']['path']['matchphrase']  #term
b = list(event['params']['querystring'].keys())[0]   #dataproduct.keyword
c = list(event['params']['querystring'].values())[0]  #health
    
body=f"{query: {{a} : {{b}: {c}}}}"
print(body)

我错过了什么吗?

【问题讨论】:

  • body = f'{{"query": {{{a}: {{{b}: {c}}}}}}}'

标签: python dictionary


【解决方案1】:

这应该可行:

body = {"query":{str(a):{str(b):str(c)}}}
print(body)

【讨论】:

    【解决方案2】:

    转义是错误的。

    试试这个:

    body = f'{{"query": {{{a!r}: {{{b!r}: {c!r}}}}}}}'
    

    我还添加了!r,它将返回对象的真实表示 (repr)(因此您无需人为添加引号)。

    【讨论】:

      【解决方案3】:

      您可以创建一个字典,然后使用json.dumps 获取它的字符串版本。

      import json
          
      event = {
          "body-json": {},
          "params": {
              "path": {"matchphrase": "term"},
              "querystring": {"dataproduct.keyword": "health"},
              "header": {"Accept": "application/json"},
          },
          "resource-path": {"matchphrase}"},
      }
          
      a = event["params"]["path"]["matchphrase"]  # term
      b = list(event["params"]["querystring"].keys())[0]  # dataproduct.keyword
      c = list(event["params"]["querystring"].values())[0]  # health
          
      result = {"query": {a: {b: c}}}
          
      print(json.dumps(result))
      

      输出:

      {"query": {"term": {"dataproduct.keyword": "health"}}}
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 2011-03-20
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多