Login

Convert tab indented string to dictionary

Author:
ekinertac
Posted:
September 21, 2017
Language:
Python
Version:
Not specified
Tags:
python tab
Score:
0 (after 0 ratings)

output:

{u'Ogrenci': [u'Tum okullar', u'Lisans', u'Onlisans', u'Yuksek Lisans / Doktora', u'Ingilizce Hazirlik'], u'Ogretim Elemani': [u'Tum okullar', u'Lisans', u'Onlisans', u'Yuksek Lisans / Doktora', u'Ingilizce Hazirlik']}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# -*- coding: utf-8 -*-
from collections import defaultdict
import pprint

data = u"""
Öğrenci
    Tüm okullar
    Lisans
    Önlisans
    Yüksek Lisans / Doktora
    İngilizce Hazırlık
Öğretim Elemanı
    Tüm okullar
    Lisans
    Önlisans
    Yüksek Lisans / Doktora
    İngilizce Hazırlık
"""

result = defaultdict(list)
current_key = None

for line in data.splitlines():
    if not line: continue  # Filter out blank lines

    # If the line is not indented then it is a key
    # Save it and move on
    if not line[0].isspace():
        current_key = line.strip()
        continue

    # Otherwise, add the value
    # (minus leading and trailing whitespace)
    # to our results
    result[current_key].append(line.strip())

pprint.pprint(dict(result))

More like this

Comments

Please login first before commenting.