简体   繁体   English

如何从python中的文件创建字典

[英]How to create a dictionary from a file in python

I have a file like this : 我有一个像这样的文件:

group #1
a b c d
e f g h

group #2
1 2 3 4
5 6 7 8

How can I make this into a dictionary like this: 我怎样才能把它变成这样的字典:

{'group #1' : [[a, b, c, d], [e, f, g, h]], 
 'group #2' :[[1, 2, 3, 4], [5, 6, 7, 8]]}
file = open("file","r")                       # Open file for reading 
dic = {}                                      # Create empty dic

for line in file:                             # Loop over all lines in the file
        if line.strip() == '':                # If the line is blank
            continue                          # Skip the blank line
        elif line.startswith("group"):        # Else if line starts with group
            key = line.strip()                # Strip whitespace and save key
            dic[key] = []                     # Initialize empty list
        else:
            dic[key].append(line.split())     # Not key so append values

print dic

Output: 输出:

{'group #2': [['1', '2', '3', '4'], ['5', '6', '7', '8']], 
 'group #1': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]}

Iterate over the file until you find a "group" tag. 遍历文件,直到找到“组”标签。 Add a new list to your dictionary with that tag. 使用该标签将新列表添加到字典中。 Then append lines to that tag until you hit another "group" tag. 然后将行附加到该标签,直到您单击另一个“组”标签。

untested 未经测试

d = {}
for line in fileobject:
    if line.startswith('group'):
        current = d[line.strip()] = []
    elif line.strip() and d:
        current.append(line.split())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM