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

可能吗?感谢您的帮助!

编辑

基字符串:

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                                    
下面是

一个示例:

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

您可以使用以下代码从原始文本创建字典:

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

也许这不是一个干净的解决方案,但可能有用。

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

最新更新