[英]Nested dictionary with lists to many dictionaries
I have nested dictionary with lists like this我有这样的列表嵌套字典
{
'a': 1,
'x':[
{'b': 1,
'c': [
{'z': 12},
{'z': 22},
]
},
{'b': 2,
'c': [
{'z': 10},
{'z': 33},
]
}
]
}
And I want to convert it to list of flat dictionaries i form like this.我想将它转换为我这样形成的平面词典列表。
[
{'a': 1, 'b': 1, 'z': 12},
{'a': 1, 'b': 1, 'z': 22},
{'a': 1, 'b': 2, 'z': 10},
{'a': 1, 'b': 2, 'z': 33},
]
Any idea how to achieve that?知道如何实现这一目标吗?
A possible solution is:一个可能的解决方案是:
#!/usr/bin/env python3
d = {
'a': 1,
'x': [
{
'b': 1,
'c': [
{'z': 12}
]
},
{
'b': 2,
'c': [
{'z': 10}
]
}
]
}
res = [{"a": 1, "b": x["b"], "z": x["c"][0]["z"]} for x in d["x"]]
print(res)
This assumes that there is only one a
(with a fixed value of 1
) and x
element and this element is added to the comprehension manually.这假设只有一个a
(固定值为1
)和x
元素,并且这个元素被手动添加到理解中。
The other two elements ( b
and z
) are taken from x
array with a list comprehension.其他两个元素( b
和z
)从带有列表推导式的x
数组中获取。
To learn more about how comprehensions work read the following:要了解有关理解如何工作的更多信息,请阅读以下内容:
PS.附注。 You are supposed to first show what you have tried so far and get help on that.您应该首先展示到目前为止您尝试过的内容并获得帮助。 Take a look at SO rules before posting your next question.在发布下一个问题之前,请查看SO 规则。
The following produces the requested result:以下生成请求的结果:
[{'a': 1, 'b': 1, 'z': 12}, {'a': 1, 'b': 2, 'z': 10}]
Use at your own risk.使用风险自负。 The following was only tested on your example.以下仅在您的示例上进行了测试。
from itertools import product
def flatten(D):
if not isinstance(D, dict): return D
base = [(k, v) for k, v in D.items() if not isinstance(v, list)]
lists = [[flatten(x) for x in v] for k, v in D.items() if isinstance(v, list)]
l = []
for p in product(*lists):
r = dict(base)
for a in p:
for d in a:
r.update(d)
l.append(r)
return l
The following tests above.以上测试如下。
d = {
'a': 1,
'x':[
{'b': 1,
'c': [
{'z': 12}
]
},
{'b': 2,
'c': [
{'z': 10}
]
}
]
}
print flatten(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.