【问题标题】:Convert list of objects to attributes将对象列表转换为属性
【发布时间】:2021-11-02 12:28:07
【问题描述】:

Google Admin SDK Reports API Activities.list() 方法返回活动事件。在记录返回的相关部分中,一个对象看起来像这样......

{
   ...,
   "events": [
      {
         "type": "call",
         "event": "call_ended",
         "paramaters": [
            {
               "name": "network_estimated_upload_kbps_mean",
               "intValue": "10"
            },
            {
               "name": "meeting_code",
               "value": "ABCDEFGH"
            },
            {
               "name": "is_external",
               "boolValue": true
            }
         ]
   ],
   ...
}

我需要将这些事件加载到数据库表中。我正在寻找一种 pythonic 和快速的方法来将参数列表转换为具有属性的对象,一旦加载,将更容易在 .所以参数会变成...

{
  "type": "call",
  "event": "call_ended",
  "parameters": {
    "network_estimated_upload_kbps_mean": 10,
    "meeting_code": "ABCDEFGH",
    "is_external": true
  }
}

我以为我会使用列表解析或 lambda 之类的东西,但我不擅长 python,并且数据类型被编码到对象的属性名称中......我无法弄清楚。

【问题讨论】:

    标签: python google-admin-sdk


    【解决方案1】:

    您可以使用defaultdict 传递原始paramaters 键的值,然后将该defaultdict 作为新字典的值传递:

    from collections import defaultdict
    true = True
    
    data = {
        "type": "call",
        "event": "call_ended",
        "paramaters": [
            {
                "name": "network_estimated_upload_kbps_mean",
                "intValue": "10"
                },
            {
                "name": "meeting_code",
                "value": "ABCDEFGH"
                },
            {
                "name": "is_external",
                "boolValue": true
                }
            ]
        }
    
    # form defaultdict with key being first value of inner dictionary 
    # and value being second value of inner dictionary
    d = defaultdict(dict)
    [d.update({list(p.values())[0]: list(p.values())[1]}) for p in data['paramaters']]
    # -> defaultdict(<class 'dict'>, {'network_estimated_upload_kbps_mean': '10', 'meeting_code': 'ABCDEFGH', 'is_external': True})
    
    new_dict = {k: v for k, v in data.items() if k != 'paramaters'}
    new_dict['paramaters'] = dict(d)
    

    new_dict 看起来像这样:

    {'type': 'call', 'event': 'call_ended', 'paramaters': {'network_estimated_upload_kbps_mean': '10', 'meeting_code': 'ABCDEFGH', 'is_external': True}}
    

    【讨论】:

    • 效果很好。谢谢。整数仍然是字符串,但我可以单独处理。
    • @StephenLloyd 出于文档目的,如果可以的话,请接受对您有帮助的答案 (✓) - 它可以帮助将来遇到相同问题的其他人也找到解决方案 :)跨度>
    • 抱歉,我投了赞成票,但忘了接受。
    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多