Print certain amount of tuples in a list without name

so my exercise was to print 10 most common words in a text file. Assuming I opened the file and created a dictionary that contains seperated words with indexes. Normally, I do this:

li=list()
for key,value in d.items():
   tpl=(value,key)
   li.append(tpl)

li=sorted(li,reverse=True)
for key,value in li[:10]:
   print('Ten most common words: ',value,key)

But prof gave me a single line of code that can replace almost all those lines:

print(sorted([(value,key) for key,value in d.items()],reverse=True))

However I can’t find a way to print only 10 tuples since the list has no name, I can’t use the for loop to print. Can you help me out?

Answer

Separate the list creation from the print():

li = sorted([(value, key) for key, value in d.items()], reverse=True)

Now you can iterate through li.

for item in li[:10]:
    print(item)

Leave a Reply

Your email address will not be published. Required fields are marked *