I have the following text file:
text1 text2
# text2 text3 text4
# text5 text4 text6
text 3 text 4
# ....
...
I would like to have a array list like the following, where fu
dict[function([text1, text2])] = [[text2, text3, text4], [text5, text4, text6]].
The idea is to open the file, read line by line
dict = {}
inputfile = open("text.txt","r")
for line in inputfile:
l=line.split()
if not line.startswith("#"):
#create a new key
else:
dict[key] = l
However, the problem is that I cannot assign other element if I go to the next line. Do you know how to solve this issue?
"Function"is just a function which I defined elsewhere and that takes as an input a list of strings.
You can use collections.defaultdict
to create a dictionary with list
s as the values to which you can append items.
from collections import defaultdict
my_dict = defaultdict(list)
with open('text.txt') as f:
key = ''
for line in f:
if not line.startswith('#'):
key = line
# key = function(line.split())
continue
my_dict[key].append(line.strip('#').split())
print(my_dict)
Output:
defaultdict(<class 'list'>,
{'text1 text2\n': [['text2', 'text3', 'text4'],
['text5', 'text4', 'text6']],
'text3 text4\n': [['text21', 'text31', 'text41'],
['text51', 'text41', 'text61']]})
Just change the key = line
line to whatever function you're passing the key to.
My text.txt
file contains:
text1 text2
# text2 text3 text4
# text5 text4 text6
text3 text4
# text21 text31 text41
# text51 text41 text61
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.