简体   繁体   English

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

[英]How to group dictionary elements into lists dynamically?

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

Would like to group the JSON content into lists as below: 要将JSON内容分为以下列表:

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

header1, header2 can be till ....header n . header1, header2 can be till ....header n So dynamically lists has to be created containing it's values as shown above. 因此,必须动态创建包含其值的列表,如上所示。

How can i achieve this ? 我怎样才能做到这一点? What's the best optimal way to approach ? 最好的最佳处理方式是什么?

SOLUTION: 解:

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. 现在, header1header2可以作为列表访问。

for i in header1:
    print i

Assuming you read the JSON into a variable d (maybe using json.loads ), you could iterate over the keys (sorted?) and build the lists with the keys of current value: 假设您将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))

Fixing your json structure: 修复您的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"
          }
    }
}

And then loading and creating lists: 然后加载并创建列表:

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]))

Gives: 得到:

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

Once you load your json, you can get the list you want for any key by doing something like the following ( headers variable below is a placeholder for your loaded json). 加载json后,您可以通过执行以下操作来获取任何键所需的列表(下面的headers变量是加载的json的占位符)。 You don't need to convert it to a list to work with it as an iterable but wrapped it in list(...) to match the output in your question. 您无需将其转换为列表即可以迭代方式使用它,而是将其包装在list(...)以匹配问题中的输出。

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

If you need to actually store the list of keys for each of your "header" dicts in some sort of accessible format, then you could create another dictionary that contains the lists you want. 如果您实际上需要以某种可访问的格式存储每个“标头”字典的键列表,则可以创建另一个包含所需列表的字典。 For example: 例如:

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']}

You can use recursion: 您可以使用递归:

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()}

Output: 输出:

{'header1': ['header1_body1', 'header1_body2'], 'header2': ['header2_body1', 'header2_body2']}
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM