-1

I have two lists. one of candidates and one of votes received. I want to sort them descending by votes received. Zipping works fine. When I print the type of the resultant list it comes back as class 'list'. Next I sort and, bam!, get an AttributeError: 'tuple' object has no attribute get. I don't know how to fix this and would appreciate guidance.

for i in range(len(uniquecandidate)):
    result = zip(uniquecandidate, votes) # zips two lists together  

result_list = list(result)
print(type(result_list))   # returns <class 'list'>

result_list.sort(key=lambda x: x.get('votes'), reverse=True) #sort by vote number

print(result_list, end='\n\n')
                                                   

Code and Error

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Wolfe
  • 77
  • 2
  • 9

2 Answers2

3

zip returns a list of tuples; you can sort them by accessing the elements with their index:

result_list.sort(key=lambda x: x[1], reverse=True)

if you like to be more explicit, you can use collections.namedtuple, and access the element via dot notation on the attribute name:

from collections import namedtuple


Poll = namedtuple('Poll', ['candidate', 'numvotes'])

uniquecandidate = ['a', 'b', 'c', 'd']
votes = [3, 4, 7, 1]

poll_results = list(map(Poll, uniquecandidate, votes))
poll_results.sort(key=lambda x: x.numvotes, reverse=True)

print(poll_results)

or with typing.NamedTuple:

from typing import NamedTuple

class Poll(NamedTuple):
    candidate: str
    numvotes: int

uniquecandidate = ['a', 'b', 'c', 'd']
votes = [3, 4, 7, 1]

poll_results = list(map(Poll, uniquecandidate, votes))
poll_results.sort(key=lambda x: x.numvotes, reverse=True)

print(poll_results)

out:

[Poll(candidate='c', numvotes=7), Poll(candidate='b', numvotes=4), Poll(candidate='a', numvotes=3), Poll(candidate='d', numvotes=1)]
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
1

Because your candidates and votes are stored in a tuple objects, the get() method won't work on them like it would on a dictionary. I recommend switching from

x.get('votes')

to this:

x[1]

This will get index 1 of each tuple (which in your case is the vote count).

Wombo
  • 46
  • 3