Search In A Txt File Containing Tab-separated Values In Python
I have a TXT file which consists of tab-separated values of the following form (3 columns): type color name fruit red apple fruit red grape vegetable gr
Solution 1:
Here is a way how you can do something like it. It is not exactly what you want, but it works:
data = {}
with open('file_name.txt', 'r') as f:
lines = [line.rstrip() for line in f]
lines.pop(0)
for line in lines:
x = line.split('\t')
try:
data[x[0]][x[1]].append(x[2])
except KeyError:
data.update({x[0]: {x[1]: []}})
data[x[0]][x[1]].append(x[2])
print(data['fruit']['red'])
-> ['apple', 'grape']
print(data['vegetable']['green'])
-> ['cucumber']
Post a Comment for "Search In A Txt File Containing Tab-separated Values In Python"