从嵌套字典创建列表

时间:2017-08-08 16:48:42

标签: python list dictionary

我想创建一个由字典键组成的列表,但这些字典嵌套在列表中。例如,给出以下JSON:

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

我想创建每个test_case变量中所有键的列表 - 示例输出将是:

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)

我有完成此操作的代码,但似乎不必要地复杂......

libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "2.1.0",
"org.apache.spark" %% "spark-sql" % "2.1.0",
"org.apache.spark" %% "spark-streaming" % "2.1.0",
"org.apache.spark" %% "spark-mllib" % "2.1.0"
)

2 个答案:

答案 0 :(得分:3)

您可以像这样使用列表理解

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

请注意,不保证每个内部字典的键的顺序,因为在&lt;中没有排序。 Python 3.6

答案 1 :(得分:1)

此列表理解对格式错误的数据更为宽容(例如,它会忽略不包含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']

虽然上面的代码是有效的,但这更具可读性:

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