<p>递归函数也可用于:</p>
<pre class="lang-py prettyprint-override"><code>from pprint import pprint
data = [
{
"frame_id": 1,
"filename": "/content/drive/MyDrive/Clocks/clock.jpg",
"objects": [
{"class_id": 74, "name": "clock",
"relative_coordinates": {"center_x": 0.497010, "center_y": 0.561621, "width": 0.300727,
"height": 0.557968}, "confidence": 0.754266}
]
},
{
"frame_id": 2,
"filename": "/content/drive/MyDrive/Clocks/clock2.jpg",
"objects": [
{"class_id": 74, "name": "clock",
"relative_coordinates": {"center_x": 0.651665, "center_y": 0.511030, "width": 0.673170,
"height": 1.007840}, "confidence": 0.935582}
]
}
]
def flatten(x):
if isinstance(x, dict):
new_dict = {}
for k, v in x.items():
if isinstance(v, dict):
new_dict.update(v)
elif isinstance(v, list) and v and isinstance(v[0], dict):
for e in v:
new_dict.update(flatten(e))
else:
new_dict[k] = v
return new_dict
return x
result = [flatten(d) for d in data]
pprint(result)
</code></pre>
<p>输出:</p>
<pre><code>[{'center_x': 0.49701,
'center_y': 0.561621,
'class_id': 74,
'confidence': 0.754266,
'filename': '/content/drive/MyDrive/Clocks/clock.jpg',
'frame_id': 1,
'height': 0.557968,
'name': 'clock',
'width': 0.300727},
{'center_x': 0.651665,
'center_y': 0.51103,
'class_id': 74,
'confidence': 0.935582,
'filename': '/content/drive/MyDrive/Clocks/clock2.jpg',
'frame_id': 2,
'height': 1.00784,
'name': 'clock',
'width': 0.67317}]
</code></pre>
<p>或者,如果您使用的是Python 3.9+,则可以替换所有出现的:</p>
<pre><code>new_dict.update(v)
</code></pre>
<p>使用<a href="https://www.python.org/dev/peps/pep-0584/" rel="nofollow noreferrer">^{<cd1>} union</a>运算符:</p>
<pre><code>new_dict |= v
</code></pre>