我想提取一个包含特定字段的数组。 循环在“d”的对象中并存储“data2”的所有字段。 在这种情况下,我们将有Array_ = [“Title col1”,“Title col2”,“Title col3”]
d = {
"row1": {
"data1": "0.87",
"data2": "Title col1",
"data3": "14.4878",
"data4": "Title row1"
},
"row2": {
"data1": "15352.3",
"data2": "Title col2",
"data3": "14.9561",
"data4": "Title row2"
},
"row3": {
"data1": "0",
"data2": "Title col3",
"data3": "16.8293",
"data4": "Title row3"
}
}
}
答案 0 :(得分:1)
您可以使用list comprehension,就像这样
print [v["data2"] for v in d.values()]
<强>输出强>
['Title col1', 'Title col2', 'Title col3']
答案 1 :(得分:0)
您可以使用list comprehension:
>>> d = {
... "row1": {
... "data1": "0.87",
... "data2": "Title col1",
... "data3": "14.4878",
... "data4": "Title row1"
... },
... "row2": {
... "data1": "15352.3",
... "data2": "Title col2",
... "data3": "14.9561",
... "data4": "Title row2"
... },
... "row3": {
... "data1": "0",
... "data2": "Title col3",
... "data3": "16.8293",
... "data4": "Title row3"
... }
... }
>>> Array_ = [x["data2"] for x in d.values()]
>>> Array_
['Title col1', 'Title col2', 'Title col3']
>>>
请注意,上述代码假定d.values
返回的所有项都有"data2"
项。但是,如果情况并非如此,那么您可以使用dict.get
来避免KeyError
:
Array_ = [x.get("data2") for x in d.values()]