Login

Convert tab indented string to dictionary

Author:
ekinertac
Posted:
September 21, 2017
Language:
Python
Version:
Not specified
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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.