简体   繁体   中英

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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