#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    44
    Rep Power
    2

    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
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2009
    Posts
    475
    Rep Power
    33
    There is an error on the following line and an indentation error after the last for() loop. Please test your code before posting.
    Code:
    elif if input_word == 'all' and 'Hello' in line: #input_word is another function in which i can use values such as
    Code:
    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
    Last edited by dwblas; November 30th, 2012 at 12:48 PM.

IMN logo majestic logo threadwatch logo seochat tools logo