我想把字典弄平。词典可能包含列表。因此,在扁平化字典中的列表时,应该将列表索引作为其键。
我该怎么做?
我尝试过:
def flatten(d, parent_key='', sep='__'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
这是平整的字典,但忽略了列表。
我也尝试添加if isinstance(v, list):
,但是在append
中却没有获得如何extend
/ items
的信息。
data = {
"checksum": "c540fcd985bf88c87e48c2bfa1df5498",
"data": {
"sampleMetrics": {
"name": "DNA Library QC Metrics",
"passQualityControl": "true",
"metrics": [{
"name": "CONTAMINATION_SCORE",
"value": 1302,
"LSL": 0,
"USL": 3106,
"UOM": "NA"
}]
}
}
}
print flatten(data)
我得到的输出:
{
'checksum': 'c540fcd985bf88c87e48c2bfa1df5498',
'data__sampleMetrics__metrics': [{
'LSL': 0,
'USL': 3106,
'name': 'CONTAMINATION_SCORE',
'value': 1302,
'UOM': 'NA'
},{ 'demo': 11}],
'data__sampleMetrics__name': 'DNA Library QC Metrics',
'data__sampleMetrics__passQualityControl': 'true'
}
除了列表元素之外,还有哪些其他功能可以弄平。
预期输出:它也应该使列表变平。(通过将列表索引作为键。)
{
'checksum': 'c540fcd985bf88c87e48c2bfa1df5498',
'data__sampleMetrics__metrics__0__LSL': 0,
'data__sampleMetrics__metrics__0__USL': 3106,
'data__sampleMetrics__metrics__0__name': 'CONTAMINATION_SCORE',
'data__sampleMetrics__metrics__0__value': 1302,
'data__sampleMetrics__metrics__0__UOM': 'NA',
'data__sampleMetrics__metrics__1__demo': 11,
'data__sampleMetrics__name': 'DNA Library QC Metrics',
'data__sampleMetrics__passQualityControl': 'true'
}
如何通过将其索引视为键来拼合包含列表的字典?
答案 0 :(得分:2)
由于列表不是映射而是序列,因此您需要为其添加一个案例:
flatten(vv, new_key + sep + str(kk), sep).items() for kk, vv in enumerate(v)
打开包装:
items
获取列表中每个项目的拼合输出,并使用索引作为新的 new 键。然后,我们将所有这些结合起来以获得一个列表,并以此扩展items
。 (或者您可以遍历每个变量并重复扩展f([9,-10,-30,0,22,0,-40], L).
L = [[9], [-10, -30], [0, 22, 0], [-40]]
...。)
答案 1 :(得分:2)
您还需要检查列表-它们不是MutableMapings-因此它们当前属于您的else:
部分,并按原样添加:
import collections
from itertools import chain
def flatten(d, parent_key='', sep='__'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
elif isinstance(v, list):
for idx, value in enumerate(v):
items.extend(flatten(value, new_key + sep + str(idx), sep).items())
else:
items.append((new_key, v))
return dict(items)
data = {
"checksum": "c540fcd985bf88c87e48c2bfa1df5498",
"data": {
"sampleMetrics": {
"name": "DNA Library QC Metrics",
"passQualityControl": "true",
"metrics": [{
"name": "CONTAMINATION_SCORE",
"value": 1302,
"LSL": 0,
"USL": 3106,
"UOM": "NA"
},{ 'demo': 11}]
}
}
}
print flatten(data)
输出:
{'data__sampleMetrics__metrics__0__LSL': 0,
'checksum': 'c540fcd985bf88c87e48c2bfa1df5498',
'data__sampleMetrics__metrics__0__name': 'CONTAMINATION_SCORE',
'data__sampleMetrics__metrics__1__demo': 11,
'data__sampleMetrics__metrics__0__UOM': 'NA',
'data__sampleMetrics__metrics__0__USL': 3106,
'data__sampleMetrics__metrics__0__value': 1302,
'data__sampleMetrics__passQualityControl': 'true',
'data__sampleMetrics__name': 'DNA Library QC Metrics'}
要获得“排序的”输出,您需要在python 2.x中使用OrderedDict:
从集合中导入OrderedDict
data = OrderedDict(sorted(flatten(data).items()))
print data
输出:
OrderedDict([('checksum', 'c540fcd985bf88c87e48c2bfa1df5498'),
('data__sampleMetrics__metrics__0__LSL', 0),
('data__sampleMetrics__metrics__0__UOM', 'NA'),
('data__sampleMetrics__metrics__0__USL', 3106),
('data__sampleMetrics__metrics__0__name', 'CONTAMINATION_SCORE'),
('data__sampleMetrics__metrics__0__value', 1302),
('data__sampleMetrics__metrics__1__demo', 11),
('data__sampleMetrics__name', 'DNA Library QC Metrics'),
('data__sampleMetrics__passQualityControl', 'true')])