Home > Software design >  Python: Value disappears from the list when using groupby and converting to a dictionary
Python: Value disappears from the list when using groupby and converting to a dictionary

Time:07-07

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

CodePudding user response:

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)
  • Related