2

I'm trying to sort a dictionary by values but my code has been erroring. I have three files consisting of scores (in the format "Bob:4", with line breaks between each score.

for k in d.keys(): nlist = d[k][-3:] for v in nlist: nlist2 = max(nlist) sortd = sorted(nlist2.items(), key=lambda x: x[1]) print('{}: {} '.format(k, sortd)) 

This resulted in error "AttributeError: 'list' object has no attribute 'items'".

What is causing this error?

4
  • You are sorting nlist ? is it a list ? Commented Apr 23, 2015 at 8:26
  • as @itzmeontv implies, put a print(d) in before your for k loop to make sure you have what you think you have Commented Apr 23, 2015 at 8:32
  • Sorry, I made a mistake. I'm trying to sort the values of nlist2 (the maximum for each user) and then print them out in a list, with the names next to them (in order of highest to lowest)# Commented Apr 23, 2015 at 8:32
  • To be clear: you want to go through the whole list of k in d and find the max of last three entries in d[k]. Then put that in a new dictionary, then sort that and finally print it. Is that right? Commented Apr 23, 2015 at 9:05

3 Answers 3

2

Try it with sortd = sorted(nlist, key=lambda x: x[1]) and see if that gets what you wanted.

Sign up to request clarification or add additional context in comments.

Comments

0

for revised question you could:

nlist2 = {k:max(d[k][-3:]) for k in d} sortd = sorted(nlist2.items(), key=lambda x: x[1]) for a in sortd: print('{}: {} '.format(a[0], a[1])) 

or use -x[1] if you want highest first

Comments

0

sortd = sorted(nlist.items(), key=lambda x: x[1])

This code here use nlist but it is a list according to nlist = d[k][-3:]

2 Comments

@Morb The original code have an error msg here, and I just answer with the reason.
Sorry, I'm mixing up nlist and nlist2 here, he was trying to sort nlist2.items() which is an int

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.