python - 从列表元素形成字典

标签 python list dictionary split

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

['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/

相关文章:

list - 在 Dart 中显示没有重复项的列表 <Map>

jquery - jQuery 是否总是按照 DOM 在代码中出现的顺序迭代它们?

python - 从具有 True 的列列表的字典中创建一个 pandas 数据框

Python-如何同时读取多个文件并记录数据

list - 如何修改列表中的结构项?

json - 使用ansible映射从json获取值

python - Django:通过外键查找所有反向引用

python - 在 Python 中合并交叉表

python - 如何在 Procfile 中运行两个进程?

python - 如何对类实例列表进行排序