简体   繁体   English

从嵌套字典创建列表

[英]Create List from Nested Dictionary

I'd like to create a list that is composed of dictionary keys, but those dictionaries are nested within a list. 我想创建一个由字典键组成的列表,但是那些字典嵌套在列表中。 For example, given the below JSON: 例如,给定以下JSON:

{
    "test_cases": [{
            "name": "first request",
            "request": {
                "url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
            },
            "variables": {
                "var1": "some stuff",
                "var2": "some other stuff"
            }
        },
        {
            "name": "second request",
            "request": {
                "url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
            },
            "variables": {
                "var3": "some new stuff",
                "var4": "some other new stuff"
            }
        }
    ]
}

I'd like to create list of all of the keys from each test_case's variables - Sample output would be: 我想从每个test_case的变量创建所有键的列表-示例输出为:

list = ['var1', 'var2', 'var3', 'var4]

I have code that accomplishes this, but it seems unnecessarily complicated... 我有完成此任务的代码,但似乎不必要地复杂...

test_var_names = [list(test['variables'].keys()) for test in data['test_cases']]
i =0
while i < len(test_var_names):
    test_var_name = test_var_names[i]
    if isinstance(test_var_name, list):
        for item in test_var_name:
            test_var_names.append(item)
        test_var_names.remove(test_var_name)
        i = i-1
    i += 1
print (test_var_names)

You can use a list comprehension like so: 您可以像这样使用列表理解

lst = [k for d in dct['test_cases'] for k in d['variables'].keys()]
# ['var1', 'var2', 'var4', 'var3']

Note that the order of the keys for each inner dict is not guaranteed since dicts are not ordered in < Python 3.6 请注意,不能保证每个内部dict的键顺序,因为dict在<Python 3.6中没有排序

This list comprehension is more forgiving to malformed data (eg it would ignore data that did not contain variables ). 这种列表理解更能容忍格式错误的数据(例如,它将忽略不包含variables数据)。

d = {
    "test_cases": [{
            "name": "first request",
            "request": {
                "url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
            },
            "variables": {
                "var1": "some stuff",
                "var2": "some other stuff"
            }
        },
        {
            "name": "second request",
        },
        {
            "name": "third request",
            "request": {
                "url": "{{env_base_url}}/v2/597649d3110000be08b1be84/{{env_userName}}"
            },
            "variables": {
                "var3": "some new stuff",
                "var4": "some other new stuff"
            }
        }
    ]
}

>>> [var 
     for sublist in [case.get('variables', {}).keys() for case in d.get('test_cases', [])]
     for var in sublist]
['var1', 'var2', 'var4', 'var3']

Although the code above is efficient, this is more readable: 尽管上面的代码很有效,但是可读性更高:

variables = []
items = d.get('test_cases')
for item in items:
    variables.extend(item.get('variables', {}).keys())

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

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