简体   繁体   中英

Printing a text file as a dictionary python

Text file I am working on

3:d:10:i:30
1:d:10:i:15
4:r:30
1:r:15
2:d:12:r:8
4:l:20
5:i:15
3:l:20:r:22
4:d:30
5:l:15:r:15

I am trying to print a dictionary from a text file that should come out looking like :

{1: {'d': 10, 'i': 15, 'r': 15},
2: {'d': 12, 'r': 8},
3: {'d': 10, 'i': 30, 'l': 20, 'r': 22},
4: {'d': 30, 'l': 20, 'r': 30},
5: { 'i': 15, 'l': 15, 'r': 15}}

Instead my code is overiding each line in the file and only takes the most recent line as the value in the dictionary so it looks like:

 {'3': {'l': '20', 'r': '22'}, 
 '1': {'r': '15'}, 
 '4': {'d': '30'}, 
 '2': {'d': '12', 'r': '8'}, 
 '5': {'l': '15', 'r': '15'}})

This is what I have so far

def read_db(file):
d = defaultdict(dict)
for line in open('db1.txt'):
    z = line.rstrip().split(':')
    d[z[0]]=dict( zip(z[1::2],z[2::2]))
print(d)

I tried doing += but that operand is not working on the dict. I am a bit stuck. Thanks for any help

This is one approach using a simple iteration and dict.setdefault .

Ex:

res = {}
with open(filename) as infile:           #Open file to read
    for line in infile:                  #Iterate Each line 
        line = line.strip().split(":")   #Split by colon
        res.setdefault(line.pop(0), {}).update(dict(zip(line[::2], line[1::2])))    

print(res)

Output:

{'1': {'d': '10', 'i': '15', 'r': '15'},
 '2': {'d': '12', 'r': '8'},
 '3': {'d': '10', 'i': '30', 'l': '20', 'r': '22'},
 '4': {'d': '30', 'l': '20', 'r': '30'},
 '5': {'i': '15', 'l': '15', 'r': '15'}}

Or using collections.defaultdict

Ex:

from collections import defaultdict
res = defaultdict(dict)
with open(filename) as infile:
    for line in infile:
        line = line.strip().split(":")
        res[line.pop(0)].update(dict(zip(line[::2], line[1::2])))

print(res)

Output:

defaultdict(<class 'dict'>,
            {'1': {'d': '10', 'i': '15', 'r': '15'},
             '2': {'d': '12', 'r': '8'},
             '3': {'d': '10', 'i': '30', 'l': '20', 'r': '22'},
             '4': {'d': '30', 'l': '20', 'r': '30'},
             '5': {'i': '15', 'l': '15', 'r': '15'}})

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