如何将字典元素动态分组为列表?

时间:2018-12-01 14:36:12

标签: python json list dictionary group-by

I have JSON file as mentioned below,
**test.json**

    {
    "header1" :
       {
           "header1_body1":
              {
               "some_key":"some_value",
                .......................
              },
          "header1_body2":
              {
                "some_key":"some_value",
                 .......................
              }

       },
    "header2":
       {
          "header2_body1":
              {
               "some_key":"some_value",
                .......................
              },
          "header2_body2":
              {
                "some_key":"some_value",
                 .......................
              }
    }
}

想要将JSON内容分为以下列表:

header1 = ['header1_body1','header1_body2']
header2 = ['header2_body1','header2_body2']

header1, header2 can be till ....header n。因此,必须动态创建包含其值的列表,如上所示。

我该如何实现? 最好的最佳方式是什么?

解决方案:

with open('test.json') as json_data:
      d = json.load(json_data)

for k,v in d.iteritems():
      if k == "header1" or k == "header2":
            globals()['{}'.format(k)] = d[k].keys()

现在,header1header2可以作为列表访问。

for i in header1:
    print i

5 个答案:

答案 0 :(得分:0)

假设您将JSON读入变量d(也许使用json.loads),则可以遍历键(排序?)并使用当前值的键构建列表:

for key in sorted(d.keys()):
    l = [x for x in sorted(d[key].keys())]  # using list comprehension
    print(key + ' = ' + str(l))

答案 1 :(得分:0)

修复您的json结构:

{
"header1" :
   {
       "header1_body1":
          {
           "some_key":"some_value"
          },
      "header1_body2":
          {
            "some_key":"some_value"
          }

   },
"header2":
    {
      "header2_body1":
          {
           "some_key":"some_value"
          },
      "header2_body2":
          {
            "some_key":"some_value"
          }
    }
}

然后加载并创建列表:

header = []

for key, value in dictdump.items():

    header.append(list(value.keys()))

for header_num in range(0, len(header)):
    print("header{} : {}".format(header_num + 1, header[header_num]))

礼物:

header1 : ['header1_body1', 'header1_body2']
header2 : ['header2_body1', 'header2_body2']

答案 2 :(得分:0)

一旦加载json,就可以通过执行以下操作来获取想要的任何键的列表(以下headers变量是加载的json的占位符)。您无需将其转换为列表即可迭代使用,只需将其包装在list(...)中即可匹配问题中的输出。

list(headers['header1'].keys())

如果您需要以某种可访问的格式实际存储每个“标头”字典的键列表,则可以创建另一个包含所需列表的字典。例如:

import json

data = """{
    "header1" : {
        "header1_body1": {
             "some_key":"some_value"
             },
        "header1_body2": {
            "some_key":"some_value"
            }
        },
    "header2": {
        "header2_body1": {
            "some_key":"some_value"
            },
        "header2_body2": {
            "some_key":"some_value"
            }
        }
    }"""

headers = json.loads(data)

# get the list of keys for a specific header
header = list(headers['header1'].keys())
print(header)
# ['header1_body1', 'header1_body2']

# if you really want to store them in another dict
results = {h[0]: list(h[1].keys()) for h in headers.items()}
print(results)
# OUTPUT
# {'header1': ['header1_body1', 'header1_body2'], 'header2': ['header2_body1', 'header2_body2']}

答案 3 :(得分:0)

您可以使用递归:

d = {'header1': {'header1_body1': {'some_key': 'some_value'}, 'header1_body2': {'some_key': 'some_value'}}, 'header2': {'header2_body1': {'some_key': 'some_value'}, 'header2_body2': {'some_key': 'some_value'}}}
def flatten(_d):
  for a, b in _d.items():
    yield a
    if isinstance(b, dict):
      yield from flatten(b)

new_results = {a:[i for i in flatten(b) if i.startswith(a)] for a, b in d.items()}

输出:

{'header1': ['header1_body1', 'header1_body2'], 'header2': ['header2_body1', 'header2_body2']}

答案 4 :(得分:0)

import json
with open('test.json') as json_data:
          d = json.load(json_data)

for k,v in d.iteritems():
    if k == "header1" or k == "header2":
          globals()['{}'.format(k)] = d[k].keys()

now, `header1` and `header2` can be accessed as list.

    for i in header1:
        print i