Hi I'm trying to build two seperate dictionaries with a file thats arranged in this format.
I need to take the name's reverse it so first name then last name, for the first dictionary I need to take the first name as the key and the other names in the first block as the values, ie, list of strings.
The second dictionary I need to again use the first name as the key ad the group or groups they belong to as the value.
I have figured out how to reverse the names using the comma to split them, however I end up with list of all the names which really doesnt help me seperate them at all.
Im really confusd as to how I can iterate over this to pull out these specific lines and then associate them as keys with other specific lines as values. Especially confused as to how I can get the first name as the key then the folling names as values and then skip the blank line and start again but with the new key.
Any Help would be greatly appreciated.

Text file Format:

Connors, Leah
Flying Club
Connors, Frank
Patterson, Shawn
Patterson, John

Cosmo, Calvin
Sailing buddies
Dodge ball group
Patterson, Shawn
Patterson, Sally

Connors, Frank
Rowing school
Connors, Leah
Connors, Robert

This is what I have so far but I think im really far off.. Please help

def load_profiles(profiles_file, person_to_friends, person_to_networks):
    f = open('profiles.txt', 'r')
    current_line = line
    previous_line = line - 1
    next_line = line + 1
    for line in f:
       if line.__contains__(','):
           key = reverse_name(current_line)
                if not next_line.__contains__(','):
           try:
                person_to_networks[key].append(line)
            except KeyError:
                person_to_networks[key] = [key]""

You refer to line even it only gets define in for of line 6 already at lines 3 to 5. What adding/substracting 1 from the input line is supposed to mean?

Please, use in, not __contains__ method. What is [key]"" is supposed to mean?

lol yeh, what I was attempting to do was be able to run if statements on multiple lines at once in order to determinewhich line I was looking
at since the format of the file will always look like that. The key is suppose to be the key for the dictionary, which in this case will always
be the first line reversed without a comma, I already wrote a helper function to reverse the line witch is working.
so for the dict( person_to_friends) the first block should be like this sorry dont know why it turned into a link {'Leah Connors' : ['Frank Connors', Shawn Patterson, John Patterson']} The second (dic person_to_networks) {'Leah Connors' : ['Flying Club']}
and the dictionarys keep adding new keys or updating as they go through subsequent paragraphs.
I think I have made substantial progress on my code from what there but it is still non functioning, I have attempted to do it with for loops, but Iam unaware how to iterate through past and future lines at once. So i decided to start working with a while loop however as you can tell from my code my knowledge is sub par and even more so for while loops.. but I do suspect Im getting closer here is what I have now

Code blocks are created by indenting at least 4 spaces
... and can span multiple lines


 def load_profiles(profiles_file, person_to_friends, person_to_networks):
f = open('profiles.txt')
lines = f.readlines()
tmp = []
person_to_networks = {}
line_number = 0
while line_number < len(lines)+1:
    prev_line = lines[line_number-1]
    line = lines[line_number]
    from_line = lines[line_number+1]
    header_line = lines[line_number+2]

    if line.__contains__(',') and not from_line.__contains__(',') and not from_line.isspace():
        key = reverse_name(line)
        new = reverse_name(from_line)
        try:
            person_to_networks[key].append(new)
        except KeyError:
            person_to_networks[key] = [new]
        if not line.__contains__(',') and not line.isspace():
            try:
                person_to_networks[key].append(new)
            except KeyError:
                person_to_networks[key] = [new]
line_number += 3

print person_to_networks 

The print statement was just to help me see if Im making progress
Also in it I had to define person_to_network to an empty dict but in reality the imputed dict's will may or may not be empty.. I think i might need something like person_to_network = person_to_network and the same for person_to_friends
I would assume there's a much simpler way to achieve what Im trying to do, I hope my expanation of what I'm going for is clear enough.

indention is off, line_number stays zero and you have infinite loop, you still use __contains___, line 24 condition can not be True when line 17 condition is True, you are overwriteing one parameter to the function and others are never used.....

Write code one step at the time and verify that is working, otherwise you get a mess.

Some info on what you are trying to do
Reading Files
Lists and Dictionaries or http://www.diveintopython.net/native_data_types/lists.html and http://www.diveintopython.net/native_data_types/index.html#odbchelper.dict

See if this code helps get you started

f = open('profiles.txt', 'r').readlines()
for line in f:
    line = line.strip()
    print line

    if "," in line:
        line_as_list = line.split(',')
        if len(line_as_list) > 1:
            print "     ", line_as_list[1].strip(), line_as_list[0].strip()

Im not really sure what the print statments are for ? im attempting to build a dictionary i get that its being split the comma but in mine the reverse_name(line) function already reversed the first and last name and removed the comma. My code has advanced quit a bit from the version posted there I almost had a working one for people : networks but for some reason I could get the keys right but would end up with two copies of the value.. Unfortnalty I have altered the code more since then ad have seen a steady deterioration in the wrong direction and dont remember how it was b4 lol, plus I oly have a few hours left to complete it.. at this point im now getting corect keysbut the keys now have all th values for each one..

I need to take the first name as the key and the other names in the first block as the values, ie, list of strings.

Adding to a dictionary is pretty straight forward (code is not tested)

first_name_dict = {}
f = open('profiles.txt', 'r').readlines()
for line in f:
    line = line.strip()
    print line
    if "," in line:
        line_as_list = line.split(',')
        if len(line_as_list) > 1:
            first_name = line_as_list[1].strip()
            last_name = line_as_list[0].strip()
            print "     ", first_name, last_name
            if first_name in first_name_dict:
                first_name_dict[first_name].append(last_name)
            else:
                first_name_dict[first_name]=[last_name]

print first_name_dict

Are members of the group the name before or after "Flying Club", etc. In any case you want to store the names in a list if there is a comma, and do something with that list when there isn't a comma in the record.

I may have figured out what you mean. For future reference, you should post the input and what you expect the output to look like. This should get you started but is not a complete solution as it is your homework.

data="""Connors, Leah
 Flying Club
 Connors, Frank
 Patterson, Shawn
 Patterson, John

Cosmo, Calvin
 Sailing buddies
 Dodge ball group
 Patterson, Shawn
 Patterson, Sally

Connors, Frank
 Rowing school
 Connors, Leah
 Connors, Robert"""
#
f=data.split("\n")
#f = open('profiles.txt', 'r').readlines()
group=[]
for rec in f:
    rec = rec.strip()
    if len(rec):     ## not a blank record
        group.append(rec)
    else:
        names_list = []
        print "\ncontrol name =", group[0]
        print "club =        ", 
        for member in group[1:]:
            if "," not in member:       ## club name not person's name
                print member, "**",
            else:
                names_list.append(member)
        print
        for name in names_list:
            print name, "**",
        print
        group=[]     ## this group deleted
print "\nfinal group", group

Thanks for helping me, thats a little diferent than what Im trying to do. Sorry if I didnt explain it that clearly.
The sample text file start in the exact format as above.
An example of what the dictionary Person_to_friends would look like just using thefirst block would be
{'Leah Connors' : ['Frank Connors', Shawn Patterson, John Patterson']}
The second dict Persons_to_networks would look like this {'Leah Connors' : ['Flying Club']}
I dont know if you can spare any more time to help but I would greatly appreciate it.

I cant see how that builds a dictionary?

Printed from the above code

-------------------------------------------------------------------------------

control name = Connors, Leah
club = Flying Club **
Connors, Frank ** Patterson, Shawn ** Patterson, John **

control name = Cosmo, Calvin
club = Sailing buddies ** Dodge ball group **
Patterson, Shawn ** Patterson, Sally **

final group ['Connors, Frank', 'Rowing school', 'Connors, Leah', 'Connors, Robert']

-------------------------------------------------------------------------------

An example of what the dictionary Person_to_friends would look like just using the first block would be
{'Leah Connors' : ['Frank Connors', Shawn Patterson, John Patterson']}

which would be the first and third lines that print in code posted above, after reversing the names.

The second dict Persons_to_networks would look like this {'Leah Connors' : ['Flying Club']}

which would be the first and second lines that print above.

I cant see how that builds a dictionary?

..

This should get you started but is not a complete solution as it is your homework.

This is my last post in this thread. The thread appears to have regressed into a "keep asking questions until someone codes it for you" thread.

@crazy99:
have you ever tried to read documentation or any tutorials?
just vizit the links woooee gave you, then review the answers in this thread, and you'll find out how to solve your problem.

Thankx Ill do that for future reference, but since the deadline for my assignment has passed now... I think I'm gonna drink some beers
and contemplate the fact that since I didn't hand in this assignment there is a high probability i'm going to fail this class, which sux cuz I like this class and was planning on taking more computer science in the future.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.