Search code examples
pythondictionarypython-itertoolsitertools-groupby

Python: Value disappears from the list when using groupby and converting to a dictionary


I am trying to write a simple function that gives the result of a runoff vote.

I start with a nested list with names of candidates, and I would like to group them by the first element and put that into a dictionary (where the first element is the key and a nested list of all the lists with this first element is the value)

def runoff_rec(xxx):
    print(xxx)


    sortedvotes = groupby(xxx, key=lambda x: x[0])
    votesdict = {}
    for key, value in sortedvotes:
        votesdict[key] = list(value)


    print(votesdict)

at the first print, the nested list looks like this:

[['Johan Liebert', 'Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi'], 
['Daisuke Aramaki', 'Gihren Zabi', 'Johan Liebert', 'Lex Luthor'], 
['Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi', 'Johan Liebert'], 
['Johan Liebert', 'Gihren Zabi', 'Lex Luthor', 'Daisuke Aramaki'], 
['Lex Luthor', 'Johan Liebert', 'Daisuke Aramaki', 'Gihren Zabi'], 
['Gihren Zabi', 'Daisuke Aramaki', 'Johan Liebert', 'Lex Luthor']]

but when I print the dictionary it looks like this:

{'Johan Liebert': [['Johan Liebert', 'Gihren Zabi', 'Lex Luthor', 'Daisuke Aramaki']], 
'Daisuke Aramaki': [['Daisuke Aramaki', 'Gihren Zabi', 'Johan Liebert', 'Lex Luthor'], ['Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi', 'Johan Liebert']],
 'Lex Luthor': [['Lex Luthor', 'Johan Liebert', 'Daisuke Aramaki', 'Gihren Zabi']], 
'Gihren Zabi': [['Gihren Zabi', 'Daisuke Aramaki', 'Johan Liebert', 'Lex Luthor']]}

One of the values from the list (the first one) has disappeared. Any idea why that might happen?

Thank you in advance, have a beautiful day


Solution

  • i guess u want this

    def runoff_rec(xxx):
        print(xxx)
    
        xxx.sort(key=lambda x: x[0])
        sortedvotes = groupby(xxx, key=lambda x: x[0])
        votesdict = {}
        for key, value in sortedvotes:
            votesdict[key] = list(value)
    
    
        print(votesdict)
    

    groupby comment

    """ make an iterator that returns consecutive keys and groups from the iterable iterable Elements to divide into groups according to the key function. key A function for computing the group category for each element. If the key function is not specified or is None, the element itself is used for grouping. """

    consecutive is importan