0

I'm having trouble with my code sorting correctly.

def generateList(attendeeList, criteria, workshoptitle):
    for i in attendeeList:
        if(criteria == 'Workshop1'):
        criteria = 'Workshop B'
        if(i['session1'] == criteria ):
            temp = []
            temp.append((i['lastname']))
            temp.sort()
            print(temp)

The output doesn't come out sorted by lastname

['Smith']
['Robertson']
['Lovelace']
['Yu']

2 Answers 2

3

Each time through the loop, you're just printing a list with a single item in it.

temp = [] # empty list
temp.append((i['lastname'])) # list with one element
temp.sort() # list is already sorted (since it just has one element)
print(temp)

Maybe you wanted something like this:

def generateList(attendeeList, criteria, workshoptitle):
    lastnames = []
    for i in attendeeList:
        if(criteria == 'Workshop1'):
            criteria = 'Workshop B'
        if(i['session1'] == criteria ):
            lastnames.append(i['lastname'])
    lastnames.sort()
    print(lastnames)

EDIT

More idiomatic Python, and returning the list instead of printing it:

def generate_list(attendee_list, criteria, workshop_title):
    if criteria == 'Workshop1':
        criteria = 'Workshop B'
    return sorted(attendee['lastname'] for attendee in attendee_list
                  if attendee['session1'] == criteria)
Sign up to request clarification or add additional context in comments.

4 Comments

OH is that because my temp was inside the loop? So it was re creating the variable every time and placing one in it and reiterating?
@MuthaCluffer Yes exactly
@MuthaCluffer Yeah, you were assigning a new empty list to temp each time.
palm to forehead, doh! Thank you very much!
0

Your code does not do what you intend. Even if you do print the item each time you get it, you generate an empty list at each iteration.

You want to create the list before the loop, in the function body, then append to it, then sort it, then iterate through it if you want to additionally print it :

def generateList(attendeeList, criteria, workshoptitle):
    temp = []

    if criteria == 'Workshop1':
        criteria = 'Workshop B'

    for i in attendeeList:
        if i['session1'] == criteria :
            temp.append(i['lastname'])

    temp.sort()

    for item in temp:
        print(item)

    return temp

Example run in IPython :

In [7]: generateList([dict(session1="Workshop B",lastname="test1"), dict(session1="Workshop A", lastname="test2"), dict(session1="Workshop B", lastname="test3")], "Workshop1", ...)

test1
test3

Out[7]: ['test1', 'test3']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.