如果我有这样的话,我如何在字典中列出清单:
Object {'a': '48',
'b': '24',
'c':[{'cA':'20', 'cB':'42', 'cC':'55'}, {'c1':'21', 'c2':'43','c3':'58'}],
'd':'44',
'e':'32',}
这是解析过的XML文件,在XML C中有这样的结构:
<p name = "a">48<\p>
<p name = "b">24<\p>
<list name ="C">
<item>
<cA>20<\cA>
<cB>42<\cB>
<cC>55<\cC>
<\item>
<item>
<c1>21<\c1>
<c2>43<\c2>
<c3>58<\c3>
<\item>
<\list>
<p name = "D">44<\p>
<p name = "e">32<\p>
所需的输出将是:
Object {'a':'48',
'b':'24',
'cA':'20',
'cB':'42',
'cC':'55',
'c1':'21',
'c2':'43',
'c3':'58'
'd':'44',
'e':'32'}
答案 0 :(得分:3)
假设您有固定的深度并包含&#34; flat&#34;字典(很多&#34;假设&#34;,我知道),你可以遍历输入字典并检查值的类型。
如果值为list
,请使用列表项更新输出dict,否则使用原始项更新
d= {'a1': '48',
'b': '24',
'c':[{'cA':'20', 'cB':'42', 'cC':'55'}, {'c1':'21', 'c2':'43', 'c3':'58'}],
'd':'44',
'e':'32'}
new_d = {}
for k,v in d.items():
if isinstance(v,list):
for v1 in v:
new_d.update(v1)
else:
new_d[k] = v
结果:
{'c2': '43', 'a1': '48', 'c3': '58', 'b': '24', 'cC': '55', 'd': '44', 'cA': '20', 'cB': '42', 'e': '32', 'c1': '21'}