DasKapital
DasKapital

Reputation: 73

Sorting list by values

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?

Upvotes: 2

Views: 106

Answers (3)

paddyg
paddyg

Reputation: 2233

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

Upvotes: 0

U2EF1
U2EF1

Reputation: 13261

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

Upvotes: 2

amow
amow

Reputation: 2223

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:]

Upvotes: 0

Related Questions