【发布时间】:2016-01-08 20:24:43
【问题描述】:
您好,我有如下列表,其中包含来自图像的元数据,如下所示:
['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
此代码不起作用。我也尝试过其他方法,但我无法获取格式。
【问题讨论】:
-
您是否期望字典列表作为输出(如您的第一种情况)?
-
@akira,请使用复选标记按钮接受足够的答案。这对你来说值得 +2 代表。
标签: python list dictionary split