首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表元素形成字典

从列表元素形成字典
EN

Stack Overflow用户
提问于 2015-10-11 16:03:47
回答 4查看 99关注 0票数 6

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

代码语言:javascript
复制
['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’]

我想做一个字典,用下面的格式拆分列表“:”:

代码语言:javascript
复制
{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}

目前,我已经写了一些代码,这是不工作的。

代码语言:javascript
复制
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

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

EN

回答 4

Stack Overflow用户

发布于 2015-10-11 16:18:06

您可以使用collections.OrderedDict在字典理解中使用列表理解

代码语言:javascript
复制
>>> 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')])
>>> 
票数 3
EN

Stack Overflow用户

发布于 2015-10-11 16:21:45

代码语言:javascript
复制
l = ['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 = {}

for ele in l:
    spl = ele.split(":", 2)
    if len(spl) == 3:
        k1, k2, v = spl
        d[k1] = {k2: v.split(",")}
    else:
        k,v = spl
        d[k] =   v.split() if "," in v  else v

输出:

代码语言:javascript
复制
{'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'}

要删除空格,您可以将其str.strip掉:

代码语言:javascript
复制
d = {}

for ele in l:
    spl = ele.split(":", 2)
    if len(spl) == 3:
        k1, k2, v = spl
        d[k1] = {k2.strip(): list(map(str.strip,v.split(",")))}
    else:
        k,v = spl
        d[k] = list(map(str.strip, v.split())) if "," in v  else v.strip

输出:

代码语言:javascript
复制
{'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'}

这两者实际上都与您的预期输出相匹配。

票数 3
EN

Stack Overflow用户

发布于 2015-10-11 16:22:39

如果你想处理任何级别的字典嵌套,你可以使用像下面这样的递归算法。示例:

代码语言:javascript
复制
def makedict(elem):
    if ':' in elem:
        k,v = map(str.strip, elem.split(':',1))
        return {k:makedict(v)}
    elif ',' in elem:
        elems = list(map(str.strip, elem.split(','))) #Simply map(...) for Python 2.x
        return elems
    return elem

如果你想做一本字典,你可以做-

代码语言:javascript
复制
d = {}
for elem in s:
    d.update(makedict(elem))

或者,如果你想要一个字典列表,在列表理解中为列表中的每个元素调用上面的函数,例如-

代码语言:javascript
复制
result = [makedict(elem) for elem in yourlist]

字典的演示-

代码语言:javascript
复制
>>> d = {}
>>> for elem in s:
...     d.update(makedict(elem))
...
>>> d
{'Component 2': {'Cb component': ['Quantization table 1', 'Sampling fac
>>> import pprint
>>> pprint.pprint(d)
{'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'}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33062799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档