2017-10-15 1 views
1

で私はこのようになりますリスト持っている:Python 3 - 辞書に一覧表示します。ソート言葉

['Data', '2017-10-12', 'Nr', 'lekcji', '6', 'Nauczyciel', 'Name', 'Nothing', 'Rodzaj', 'sprawdzian', 'Przedmiot', 'Math', 'Opis', 'This', 'is', 'just', 'a', 'test.', 'Data', 'dodania', '2017-10-01', '18:12:31'] 

を、私はそれがどのいくつかのキーワードをリストに変換したいです。ここに私が得たい結果があります:

{'Data': '2017-10-12', 'Nr lekcji': '6', 'Nauczyciel': 'Name Nothing', 'Rodzaj': 'sprawdzian', 'Przedmiot': 'Math', 'Opis': 'This is just a test.', 'Data dodania': '2017-10-01 18:21:32'} 

それは可能ですか?手伝ってくれてありがとう!

EDIT

ベース文字列:

Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

             2017-10-01 18:12:31          
+3

とするときではないグループに? –

+1

最初のリストはどのようにして始まりましたか?それはどこかから来て、空白で過度に分割されているようです... –

+0

これは可能ですが、何度も繰り返すことができるコードスニペットを作成するには、最初にリストを取得した方法を理解する必要があります。 –

答えて

2

ここでは一例です:

string = """Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

             2017-10-01 18:12:31 """ 

# Clean the input data by splitting by row and removing blanks 
clean = [i.strip() for i in string.split("\n") if i] 

# Assume the data is in pairs and group them in key,pair by using index 
# and index+1 in [0,2,4,6...] 
d = {clean[ind]:clean[ind+1] for ind in range(0,len(clean),2)} 

print(d) 

戻り値:

{'Data': '2017-10-12', 
'Data dodania': '2017-10-01 18:12:31', 
'Nauczyciel': 'Name Nothing', 
'Nr lekcji': '6', 
'Opis': 'This is just a test.', 
'Przedmiot': 'Math', 
'Rodzaj': 'sprawdzian'} 
1

あなたは辞書を作成するには、次のコードを使用することができます生のテキストから:

# Defined multiline variable with your raw datat 
text = """Data 
2017-10-12 


Nr lekcji 
6 


Nauczyciel 
Name Nothing 


Rodzaj 
sprawdzian 


Przedmiot 
Math 


Opis 
This is just a test. 


Data dodania 

            2017-10-01 18:12:31 """ 

# Clean the data to strip empty lines and unnecessary spaces 
cleaned = [line.strip() for line in text.split('\n') if line.strip() != ''] 

# Create a dictionary from the stripped list where the value of each key is 
# the item in the list which comes after the key 
myDict = dict(zip(cleaned[0::2], cleaned[1::2])) 

そして結果は次のとおりです。

>>> myDict 
{'Nr lekcji': '6', 
'Nauczyciel': 'Name Nothing', 
'Przedmiot': 'Math', 
'Rodzaj': 'sprawdzian', 
'Opis': 'This is just a test.', 
'Data': '2017-10-12', 
'Data dodania': '2017-10-01 18:12:31'} 
0

は、多分それはきれいな解決策ではありませんが、役に立つかもしれません。グループに項目を決定する方法を

with open('file.txt') as myfile: 
    lines = map(lambda e: e.strip(), filter(lambda e: len(e) > 0, myfile.read().split('\n'))) 
    # or in 3 lines 
    # raw_lines = myfile.read().split('\n') 
    # nonzero_length_lines = filter(lambda e: len(e) > 0, raw_lines) 
    # lines = map(lambda e: e.strip(), nonzero_length_lines) 
    h = {} 
    i = 0 
    while i<len(lines)-1: 
     h[lines[i]] = lines[i+1] 
     i+=2 
    print(h) 

https://repl.it/MeO5