I'm trying to read a txt
that look like:
Animals
Dog
Cat
Bird
Cities
Paris
London
Chicago
into a dictionary. (The first line into a key followed by three lines of values, and so on) It should be looking something like this:
{"Animals":["Dog","Cat","Bird"],"Cities":["Paris","London","Chicago"]
Please help me!
import itertools
d = {}
with open("C:\path\to\text.txt", "r") as f:
lines = f.readlines()
# Separate keys from values
keys = itertools.islice(lines, 0, None, 4)
first_values = itertools.islice(lines, 1, None, 4)
second_values = itertools.islice(lines, 2, None, 4)
third_values = itertools.islice(lines, 3, None, 4)
# Set keys and values
for key in keys:
key = key.rstrip()
value1 = first_values.next().rstrip()
value2 = second_values.next().rstrip()
value3 = third_values.next().rstrip()
# Create dict
l = [value1, value2, value3]
d[key] = l