【问题标题】:Forming List Comprehension For Dictionary Inside a List of Dictionaries字典列表中字典的形成列表理解
【发布时间】:2015-10-12 18:32:23
【问题描述】:

我有一个 webservice json 响应,它是一个字典列表,值本身就是字典。像下面的例子:

[
 {
   "ET": {
          "application_environment": "Y",
          "period_process": "Y",
          "extended_options": "N",
          "reports": "Y",
          "administration_tasks": "N",
          "daily_process": "Y",
          "inquiry": "Y"
          }
 },
 {
   "SD": {
           "daily_process": "Y",
           "authorize_cashier_to_close_warranty": "Y",
           "authorize_to_update_technicians_cost": "Y",
           "authorize_to_booking": "Y",
           "authorize_to_policy_adjustments": "Y",
           "authorize_to_pre-paid_maintenance_packages": "Y",
           "authorize_to_enter_actual_time": "Y"
          }
  }
]

我有以下工作,我只是想知道是否有办法通过列表理解来做到这一点?

    parsed_response = response.json()
    from_svc = []
    for items in parsed_response:
        for values in items.values():
            for daily_process in values.get("daily_process"):
                from_svc.append(daily_process)

【问题讨论】:

  • d[0]['ET']['daily_process']
  • @JustinDanielson 如果我想获取所有daily_process 值的列表怎么办?
  • 我得去一会儿,但我回来后会回复的。您需要创建一个键值对列表的列表,然后对其进行迭代。
  • @JustinDanielson 感谢贾斯汀,我找到了一种使用 for 循环执行此操作的方法,如上所示,我如何将其转换为列表理解,这样做是否值得?

标签: python json python-3.x dictionary


【解决方案1】:

我想这就是你要找的东西?

[ values['daily_process'] for items in parsed_response 
                              for values in items.values() ]

【讨论】:

  • 是的,这就是我要找的,非常感谢。
猜你喜欢
  • 2011-03-14
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
相关资源
最近更新 更多