2015-10-11 24 views
6

Hi Tôi có danh sách như sau mà chứa dữ liệu meta từ hình ảnh như sau:Hình thành từ điển từ danh sách các yếu tố

['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’] 

Tôi muốn làm một cuốn từ điển sử dụng tách danh sách “:” trong ông sau định dạng:

{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} 

Hiện tại tôi đã viết một số mã không hoạt động.

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 

Mã này không hoạt động. Tôi cũng đã thử các cách tiếp cận khác, nhưng tôi không thể có được định dạng.

+0

Bạn có đang mong đợi danh sách từ điển của từ điển làm đầu ra (như trong trường hợp đầu tiên của bạn) không? –

+0

@akira, Vui lòng chấp nhận câu trả lời đầy đủ với nút dấu kiểm. Nó có giá trị +2 đại diện cho bạn. – kdbanman

Trả lời

3

Bạn có thể sử dụng một sự hiểu biết danh sách trong một sự hiểu biết dict sử dụng 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')]) 
>>> 
1

Bạn thanh lịch có thể giải quyết vấn đề bằng cách sử dụng đệ quy, và một giới hạn chia (đối số thứ hai của split thể được sử dụng để hạn chế chia count):

def make_dict(l): 
    d = dict() 
    for elem in l: 
     key, value = elem.split(':', 1) 
     if ':' in value: 
      d[key] = make_dict([value]) 
     else: 
      d[key] = value 
    return d 

và thử nghiệm dường như để phù hợp với mong đợi của bạn:

>>> 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'] 
>>> make_dict(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'} 
+0

Cảm ơn bạn rất nhiều. Tôi thực sự hữu ích – akira

3
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 

Output:

{'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'} 

Để loại bỏ các khoảng trắng, bạn có thể str.strip nó đi:

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 

Output:

{'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'} 

Cả hai trong số đó thực sự phù hợp với sản lượng dự kiến ​​của bạn.

2

Bạn có thể sử dụng thuật toán đệ quy như thuật toán dưới đây, nếu bạn muốn xử lý bất kỳ mức độ lồng ghép từ điển nào. Ví dụ -

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 

Nếu bạn muốn thực hiện một từ điển của từ điển, bạn có thể làm -

d = {} 
for elem in s: 
    d.update(makedict(elem)) 

Hoặc nếu bạn muốn có một danh sách các từ điển của dictionries gọi hàm trên cho từng phần tử trong danh sách của bạn trong một hiểu danh sách, ví dụ -

result = [makedict(elem) for elem in yourlist] 

Demo cho từ điển của từ điển -

>>> 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'} 
+1

Đệ quy để xử lý bất kỳ mức độ làm tổ nào của từ điển –

+0

Tôi đoán '{Thành phần 1: {Y thành phần:' có nghĩa là một mệnh lệnh của dict. –

+0

Tất nhiên, tôi đã làm nó sẽ rất đơn giản để thay đổi logic từ danh sách comp để tạo ra một từ điển từ điển của từ điển, như được cập nhật trong ví dụ trên –

Các vấn đề liên quan