I'm trying to convert a text file to dictionary which I'm able to do so using defaultdict
.
The output is well and expected. But my concern now is how to do further split my values if my format of txt file is not just ":" but also with "," and "(spacing)" ? I tried insert somemore loops in but it didn't work so I removed them.
For example:
Cost : 45
Shape: Square, triangle, rectangle
Color:
red
blue
yellow
Desired output:
{'Cost' ['45']}
{'Shape' ['Square'], ['triangle'], ['rectangle'] }
{'Color' ['red'], ['blue'], ['yellow']}
Here is my current code. How should I modify it?
#converting txt file to dictionary with key value pair
from collections import defaultdict
d = defaultdict(list)
with open("t.txt") as fin:
for line in fin:
k, v = line.strip().split(":")
d[k].append(v)
print d
When you find a line with :
in it you have a key or else you have values so add the value to the last key k
:
from collections import defaultdict
d = defaultdict(list)
with open("test.txt") as fin:
for line in fin:
if ":" in line:
k, v = line.rstrip().split(":")
d[k].extend(map(str.strip,v.split(",")) if v.strip() else [])
else:
d[k].append(line.rstrip())
print(d)
Inout:
Cost : 45
Shape: Square, triangle, rectangle
Color:
red
blue
yellow
Foo : 1, 2, 3
Bar :
100
200
300
Output:
from pprint import pprint as pp
pp(d)
{'Bar ': ['100', '200', '300'],
'Color': ['red', 'blue', 'yellow'],
'Cost ': ['45'],
'Foo ': ['1', '2', '3'],
'Shape': ['Square', 'triangle', 'rectangle']}
You can change the code easily to put each value in an individual list but I would think all the values in one list would make more sense.
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.