
November 30th, 2012, 04:54 AM
|
|
Contributing User
|
|
Join Date: Oct 2012
Posts: 44
Time spent in forums: 11 h 46 m 55 sec
Reputation Power: 1
|
|
|
Changing file to dictionary:
I have a file I wanna run through in a loop. My file looks something like this:
Hello Hello
A B C D
A B C D
B C D A
B C D A
C D A B
B C D A
Hello Bye
A C D B
C D A B
A C D B
D C A B
Hello GoodBye
B C D A
A B C D
D B C A
A B C D
and I run a loop only through Bye, to blank line it should return: [from Hello Bye to blank line] i am returning one specific box of things but in my code i have an option of returning all... where my dict will include all of them added
{(A, C, D, B): 2, (C, D, A, b):1, (D, C, A, B):1}
I want to do this without using any import
So far my function looks like this:
def file_to_dict (file, input_word) # input_word = Hello or Bye
new_dict = {}
new_list = []
flag = False
for line in file:
if line.strip() == ('Hello ' + input_word):
flag = True
elif if input_word == 'all' and 'Hello' in line: #input_word is another function in which i can use values such as 'Hello' or ' Good bye' or 'Bye' or 'all'
flag = True
elif 'Hello' in line:
flag = False
elif flag == True and line.strip() != "":
new_list.append(line.split())
for next_element in new_list:
next_element = tuple(next_element)
if next_element in new_dict:
new_dict[next_element] += 1
else:
new_dict[next_element] = 1
return new_dict
Can you tell me possibly how i can do this??
Thanks
|