从列表元素形成字典

aki*_*ira 6 python dictionary split list

嗨我有如下列表,其中包含来自图像的元数据,如下所示:

['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’]
Run Code Online (Sandbox Code Playgroud)

我想使用以下格式拆分列表":"来制作字典:

{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}
Run Code Online (Sandbox Code Playgroud)

目前我写了一些不起作用的代码.

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
Run Code Online (Sandbox Code Playgroud)

此代码不起作用.我也尝试了其他方法,但我无法获得格式.

Kas*_*mvd 3

您可以使用以下命令在字典理解中使用列表理解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')])
>>> 
Run Code Online (Sandbox Code Playgroud)