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

    Join Date
    Nov 2013
    Posts
    15
    Rep Power
    0

    Help with python dictionary


    Hello,
    I want to create a function which take a file ,
    which looks like this:
    Ronaldinho,Pele
    Ronaldinho,Messi
    Romario,Pele
    Romario,Ronaldinho
    Maradona,Tevez
    Maradona,Messi
    and makes every name as the key , and the other word in the line as its value. You may think of it as lists of friends, and when I check the key of a person, the value are all his friends ( not friends of friends)
    meaning :
    d[Ronaldinho]=Pele,Messi,Romario
    d[Pele]=Ronaldinho

    d[Maradona]=Messi,Tevez
    d[Messi]=Maradona,Ronaldinho

    I am kind of lost, I am having trouble with making the file as a dictionary with several values to each key,
    I tried to make the file into a list . but then I am having trouble making the list , into a dictionary because it didn't split the names in each line. and also i don't know to add one more value to the key without replacing it.

    this is just one of my failure codes, which is stuck at splitting the names in each line.


    Code:
     
    path=open("example2.txt","r")
    print path.read()
    
    def get_social_net(path):
        d = {}
        path=open("example2.txt","r")
        your=[line.split() for line in path.readlines()]
        for i in range(len(your)):
            d[your[i][0]]=[your[i][1]]
        
       
        
        
            
        
    
        return d
    
                
        
    
        
       
        
        
    g=get_social_net(path)
    print g 
    path.close()
    could you tell me how to create this code? how to convert the file to dictionary and add several values to each key?

    i thank you for your time.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    I usually do something like what you want as follows:
    first initialize the dictionary as you do: d={}.
    Then I use the get(key[, default]) method. So where you do this: d[your[i][0]]=[your[i][1]]
    I would do this:

    d[your[i][0]]=",".join([d.get(your[i][0],""),your[0][1]])

    This will put a leading comma that you don't want so you can strip them off:
    for i in d: d[i]=d[i].lstrip(",")
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    If Ronaldinho's friends include Romario, why does Pele exclude Romario?

    Ronaldinho,Pele
    Ronaldinho,Messi
    Romario,Pele
    Romario,Ronaldinho
    Maradona,Tevez
    Maradona,Messi
    and makes every name as the key , and the other word in the line as its value. You may think of it as lists of friends, and when I check the key of a person, the value are all his friends ( not friends of friends)
    meaning :
    d[Ronaldinho]=Pele,Messi,Romario
    d[Pele]=Ronaldinho
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    15
    Rep Power
    0
    I thank you for your help , but it seems it doesn't really work for me, maybe I misunderstood what you tried to explain, because I still get errors because it doesn't separate the names as I wanted.
    let me try to rephrase what I want:
    I want to make the file as a list of list, meaning each line is a list by itself,
    so the file which contains :
    Ronaldinho,Pele
    Ronaldinho,Messi
    Romario,Pele
    Romario,Ronaldinho
    Maradona,Tevez
    Maradona,Messi

    will look like , as a list , this:
    [
    [[Ronaldinho],[Pele]]
    [ [Ronaldinho],[Messi]]
    [[Romario],[Pele]]
    [[Romario],[Ronaldinho]]
    [[Maradona],[Tevez]]
    [[Maradona],[Messi]]
    ]
    so if I have this as a list, then list[0][0]= Ronaldinho and
    list[0][1]=Pele

    from what I understood , I made the code like this:
    Code:
    path=open("example2.txt","r")
    print path.read()
    
    def get_social_net(path):
        d = {}
        path=open("example2.txt","r")
        your=[line.split() for line in path.readlines()]
        print your
        for j in your:
            your[j]=your[j].lstrip(",")
            
        for i in range(len(your)):
            d[your[i][0]]=",".join([d.get(your[i][0],""),your[0][1]])
        
        
            
        
    
        return your
    
                
        
    
        
       
        
        
    g=get_social_net(path)
    print g 
    path.close()
    could you tell me what I did wrong?
    I thank you for your time.
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,837
    Rep Power
    480
    Programming (except in lisp) is precise. You fail to specify your list as an object python would naturally print. Your program uses a dictionary whereas you say you want a list. Strings aren't shown with "quotes" as 'strings'. Your list indexing is off by 1 unless I assume this or that. In other words, we can do no better than guess your intent. rrashkin and I interpreted your question wildly differently. Not our fault.
    Code:
    import pprint
    
    def get_social_net(inf):
        return list(line.strip().split(',') for line in inf) # split at the comma
       
    with open("example2.txt","r") as inf:
        g = get_social_net(inf)
    
    pprint.pprint(g)
    
    # in python3 the output of this program is the list
    
    # [['Ronaldinho', 'Pele'],
    #  ['Ronaldinho', 'Messi'],
    #  ['Romario', 'Pele'],
    #  ['Romario', 'Ronaldinho'],
    #  ['Maradona', 'Tevez'],
    #  ['Maradona', 'Messi']]
    get_social_net is quite short, no?
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    15
    Rep Power
    0
    Originally Posted by b49P23TIvg
    Programming (except in lisp) is precise. You fail to specify your list as an object python would naturally print. Your program uses a dictionary whereas you say you want a list. Strings aren't shown with "quotes" as 'strings'. Your list indexing is off by 1 unless I assume this or that. In other words, we can do no better than guess your intent. rrashkin and I interpreted your question wildly differently. Not our fault.
    Code:
    import pprint
    
    def get_social_net(inf):
        return list(line.strip().split(',') for line in inf) # split at the comma
       
    with open("example2.txt","r") as inf:
        g = get_social_net(inf)
    
    pprint.pprint(g)
    
    # in python3 the output of this program is the list
    
    # [['Ronaldinho', 'Pele'],
    #  ['Ronaldinho', 'Messi'],
    #  ['Romario', 'Pele'],
    #  ['Romario', 'Ronaldinho'],
    #  ['Maradona', 'Tevez'],
    #  ['Maradona', 'Messi']]
    get_social_net is quite short, no?
    I am sorry to tell you, but you understood better the first time, I wanted a dictionary that has in it a list.
  12. #7
  13. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    Originally Posted by lior20088
    I thank you for your help , but it seems it doesn't really work for me, maybe I misunderstood what you tried to explain, because I still get errors because it doesn't separate the names as I wanted.
    let me try to rephrase what I want:
    I want to make the file as a list of list, meaning each line is a list by itself,
    so the file which contains :
    Ronaldinho,Pele
    Ronaldinho,Messi
    Romario,Pele
    Romario,Ronaldinho
    Maradona,Tevez
    Maradona,Messi

    will look like , as a list , this:
    [
    [[Ronaldinho],[Pele]]
    [ [Ronaldinho],[Messi]]
    [[Romario],[Pele]]
    [[Romario],[Ronaldinho]]
    [[Maradona],[Tevez]]
    [[Maradona],[Messi]]
    ]
    so if I have this as a list, then list[0][0]= Ronaldinho and
    list[0][1]=Pele

    from what I understood , I made the code like this:
    Code:
    path=open("example2.txt","r")
    print path.read()
    
    def get_social_net(path):
        d = {}
        path=open("example2.txt","r")
        your=[line.split() for line in path.readlines()]
        print your
        for j in your:
            your[j]=your[j].lstrip(",")
            
        for i in range(len(your)):
            d[your[i][0]]=",".join([d.get(your[i][0],""),your[0][1]])
        
        
            
        
    
        return your
    
                
        
    
        
       
        
        
    g=get_social_net(path)
    print g 
    path.close()
    could you tell me what I did wrong?
    I thank you for your time.
    What did you get when you ran this? Was the first "print your" output correct?

    This
    for j in your:
    your[j]=your[j].lstrip(",")
    is wrong and unnecessary.

    This
    d[your[i][0]]=",".join([d.get(your[i][0],""),your[0][1]])
    should be
    d[your[i][0]]=",".join([d.get(your[i][0],""),your[i][1]])
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    15
    Rep Power
    0
    Originally Posted by rrashkin
    What did you get when you ran this? Was the first "print your" output correct?

    This
    for j in your:
    your[j]=your[j].lstrip(",")
    is wrong and unnecessary.

    This
    d[your[i][0]]=",".join([d.get(your[i][0],""),your[0][1]])
    should be
    d[your[i][0]]=",".join([d.get(your[i][0],""),your[i][1]])
    I thank you for your response.
    now, I think I confused you a little.
    let me try to reorder things.
    the thing that should be returned from the function is the dictionary where for each person's name ( key) there is a list of value of his friends ( not friends of friends).

    friends are people's names which are in the same line.
    in simple: every name is a key, and for every name in the same line with it , is its value. so some names will have several values, and some will have few ( Tevez got only Maradona as a friend)

    I had to take the file, make from it a list, and from there to try to make from it the correct dictionary.

    now, because of your help and others I managed to overcome the first problem which is making the file into a list which is easy to use.

    now I got a problem of creating the correct dictionary.
    this is my code:
    Code:
    path=open("example2.txt","r")
    print path.read()
    
    def get_social_net(path):
        d = {}
        path=open("example2.txt","r")
        
        friends=[line.split(",") for line in path.readlines()]
        
        
       
            
        for t in range(len(friends)):
            friends[t][1]=friends[t][1].rstrip('\n')
        list2=[]
        list3=[]
        path.close()
        x=True
        for i in range(len(friends)):
            if friends[i][0] not in list2:
                
                list2.append(friends[i][0])
            if friends[i][1] not in list2:
                list2.append(friends[i][1])
    
    
        for j in range(len(list2)):
            
            
            
            for k in range (len(friends)):
                
                if list2[j]==friends[k][0]:
                    list3.append(friends[k][1])
                    
                    d[list2[j]]=list3
                    x=False 
                if x==True and  list2[j]==friends[k][1]:
                    list3.append(friends[i][0])
                    d[list2[j]]=list3                
    
            
        return d
    
    z=get_social_net(path)
    print z
    the problem I am having part with is
    Code:
    for j in range(len(list2)):
            
            
            
            for k in range (len(friends)):
                
                if list2[j]==friends[k][0]:
                    list3.append(friends[k][1])
                    
                    d[list2[j]]=list3
                    x=False 
                if x==True and  list2[j]==friends[k][1]:
                    list3.append(friends[i][0])
                    d[list2[j]]=list3                
    
            
        return d
    
    z=get_social_net(path)
    print z
    list2= the names of all the people( show's every name 1 time only .)
    and I tried to create anther list ( list 3) that I will put as value of the keys(list2) of the dictionary.
    I used to for loops.

    the problem?
    list3 just gets more values till it has all the names, and then it makes the list useless to me.

    I would love to hear a better way to do this then this way.
    I thank you for your time and attention.
  16. #9
  17. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    [CODE]>>> names='''Ronaldinho,Pele
    ... Ronaldinho,Messi
    ... Romario,Pele
    ... Romario,Ronaldinho
    ... Maradona,Tevez
    ... Maradona,Messi
    ... '''
    >>> names
    'Ronaldinho,Pele\nRonaldinho,Messi\nRomario,Pele\nRomario,Ronaldinho\nMaradona,Tevez\nMaradona,Messi \n'
    >>> lst1=names.split('\n')
    >>> lst1
    ['Ronaldinho,Pele', 'Ronaldinho,Messi', 'Romario,Pele', 'Romario,Ronaldinho', 'Maradona,Tevez', 'Maradona,Messi', '']
    >>> lst2=[i.split(',') for i in lst1]
    >>> lst2
    [['Ronaldinho', 'Pele'], ['Ronaldinho', 'Messi'], ['Romario', 'Pele'], ['Romario', 'Ronaldinho'], ['Maradona', 'Tevez'], ['Maradona', 'Messi'], ['']]
    >>> lst2.pop(-1)
    ['']
    >>> lst2
    [['Ronaldinho', 'Pele'], ['Ronaldinho', 'Messi'], ['Romario', 'Pele'], ['Romario', 'Ronaldinho'], ['Maradona', 'Tevez'], ['Maradona', 'Messi']]
    >>> d={}
    >>> for i in lst2:
    ... d[i[0]]=','.join([d.get(i[0],""),i[1]])
    ...
    >>> d
    {'Romario': ',Pele,Ronaldinho', 'Maradona': ',Tevez,Messi', 'Ronaldinho': ',Pele,Messi'}
    Last edited by rrashkin; November 21st, 2013 at 09:18 AM.

IMN logo majestic logo threadwatch logo seochat tools logo