您好,我有如下列表,其中包含来自图像的元数据,如下所示:
['Component 1: Y component: Quantization table 0, Sampling factors 1 horiz/1 vert',
'Component 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert',
'Component 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert',
'Compression Type: Progressive, Huffman', 'Content-Length: 14312', 'Content-Type: image/jpeg’]
我想使用以下格式拆分列表“:”来制作字典:
{Component 1: {Y component: [Quantization table 0, Sampling factors 1 horiz/1 vert’],
Component 2: {Cb component: [Quantization table 1, Sampling factors 1 horiz/1 vert]},
Component 3: {Cr component: [Quantization table 1, Sampling factors 1 horiz/1 vert]},
Compression Type: [Progressive, Huffman],Content-Length: 14312,Content-Type: image/jpeg}
目前我写了一些不起作用的代码。
def make_dict(seq):
res = {}
if seq[0] is not '':
for elt in seq:
k, v = elt.split(':')
try:
res[k].append(v)
except KeyError:
res[k] = [v]
print res
此代码无效。我也尝试过其他方法,但无法获取格式。
最佳答案
您可以使用 collections.OrderedDict
在字典推导中使用列表推导:
>>> li=['Component 1: Y component: Quantization table 0, Sampling factors 1 horiz/1 vert', 'Component 2: Cb component: Quantization table 1, Sampling factors 1 horiz/1 vert', 'Component 3: Cr component: Quantization table 1, Sampling factors 1 horiz/1 vert', 'Compression Type: Progressive, Huffman', 'Content-Length: 14312', 'Content-Type: image/jpeg']
>>> d=OrderedDict((sub[0],{sub[1]:sub[2:]}) if sub[2:] else (sub[0],sub[1]) for sub in [item.split(':') for item in li])
>>> d
OrderedDict([('Component 1', {' Y component': [' Quantization table 0, Sampling factors 1 horiz/1 vert']}), ('Component 2', {' Cb component': [' Quantization table 1, Sampling factors 1 horiz/1 vert']}), ('Component 3', {' Cr component': [' Quantization table 1, Sampling factors 1 horiz/1 vert']}), ('Compression Type', ' Progressive, Huffman'), ('Content-Length', ' 14312'), ('Content-Type', ' image/jpeg')])
>>>
关于python - 从列表元素形成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062799/