【问题标题】:how to access dictionary under a dictionary in python [closed]如何在python中的字典下访问字典[关闭]
【发布时间】:2018-04-06 07:37:19
【问题描述】:

`例子假设这是一个json字典-

如何将其放入下面的字典中

dictionary={
"actions": [
{
"action_type": "comment",
 "value": "1"
},
{
"action_type": "like",
"value": "18"
},
{
"action_type": "post",
"value": "4"
},
{
"action_type": "post_reaction",
 "value": "268"
},
{
"action_type": "video_view",
"value": "198245"
},
{
"action_type": "page_engagement",
"value": "198536"
},
{
"action_type": "post_engagement",
"value": "198518"
}
],
"date_start": "2018-03-30",
"date_stop": "2018-03-30"
}

我怎么能把它变成这个我尝试了迭代器,制作函数和其他方法,但我现在卡住了

dictionary={
"comment": "1"
"like": "18"
"post": "4"
"post_reaction": "268"
"video_view": "198245"
"page_engagement": "198536"
"post_engagement": "198518"
"date_start": "2018-03-30",
"date_stop": "2018-03-30"
}`

【问题讨论】:

  • 请添加您的代码以显示您尝试过的内容。
  • 如果您不分享代码,我们将无法修复您的代码。

标签: python json dictionary jupyter-notebook


【解决方案1】:

遍历action 键并创建所需的输出:

例如:

d = {}
for i in data["actions"]:
    d[i["action_type"]] = i["value"] 

d.update({"date_start": data["date_start"], "date_stop": data["date_start"]})
print(d)

字典理解

print dict((i["action_type"], i["value"]) for i in data["actions"])

输出:

{'comment': '1', 'date_stop': '2018-03-30', 'like': '18', 'date_start': '2018-03-30', 'post_engagement': '198518', 'page_engagement': '198536', 'video_view': '198245', 'post_reaction': '268', 'post': '4'}

【讨论】:

  • 嗨!它真的很有帮助,但我在 facebookads.api.Cursor 中工作。我无法迭代它。所以知道如何在这个中为facebookads.api.Cursor使用for循环
【解决方案2】:

您可以通过遍历整个字典来做到这一点。如果类型是列表,则应遍历此列表。这样做还将允许具有相似布局的其他字典(其他字典列表或字符串)由同一例程处理。

output_dict = {}
#for key, value in input_dict.items(): python 3
for key, value in input_dict.iteritems(): # python 2
      if type(value) == list:
            for item in value:
                  for key2 in item:
                        if key2 != 'value':
                              output_dict[item[key2]] = item['value']
      else:
            output_dict[key] = value

这个输出:

{'comment': '1',
 'date_start': '2018-03-30',
 'date_stop': '2018-03-30',
 'like': '18',
 'page_engagement': '198536',
 'post': '4',
 'post_engagement': '198518',
 'post_reaction': '268',
 'video_view': '198245'}

【讨论】:

    【解决方案3】:

    试试 使用 iteritems() 并检查值是否为列表

    res = {}
    for key,value in dict.iteritems():
    if isinstance(value,list):
        for item in value:
            res[item['action_type']] = item['value']
    else:
        res[key] = value
    

    输出:

    {'comment': '1',
     'date_start': '2018-03-30',
     'date_stop': '2018-03-30',
     'like': '18',
     'page_engagement': '198536',
     'post': '4',
     'post_engagement': '198518',
     'post_reaction': '268',
     'video_view': '198245'}
    

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 2022-01-25
      • 2015-11-29
      • 2014-03-18
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多