将对象列表转换为属性

Convert list of objects to attributes

Google Admin SDK 报告 API Activities.list() 方法 returns activity 事件。在记录的相关部分 return 一个对象看起来像这样...

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

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

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

我想我会使用列表理解或 lambda 之类的东西,但我不擅长 python 并且数据类型被编码到对象的 属性 名称中......我想不通。

您可以使用 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}}