Comparing and Sorting Tuples


https://www.youtube.com/embed/dZXzBXUxxCs

>>> d = {'a':10, 'b':1,'c':22}
>>> d.items()
dict_items([('a', 10), ('b', 1), ('c', 22)])
>>> sorted(d.items())
[('a', 10), ('b', 1), ('c', 22)]

Sometimes when we use the .items() it might not sort as the same like in the picture so we have sorted(d.items()) to sort them back like the same as before

>>> c = {'a':10, 'b':1,'c':22}
>>> tmp = list()
>>> for k,v in c.items():
	tmp.append((v,k))

	
>>> print(tmp)
[(10, 'a'), (1, 'b'), (22, 'c')]
>>> tmp = sorted(tmp,reverse = True)
>>> print(tmp)
[(22, 'c'), (10, 'a'), (1, 'b')]
>>>

fhand = open('words.txt')
counts = dict()
for line in fhand:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word,0) + 1
        
lst = list()
for k,v in counts.items():
    newtup = (v,k)
    lst.append(newtup)
   
lst = sorted(lst,reverse = True)

for v,k in lst[:10]:
    print(k,v)

Output

to 16
the 6
we 5
our 5
of 5
do 5
computers 5
and 5
you 4
that 4

Explanation

fhand = open('words.txt') counts = dict()

open the file and create the new dictionary

for line in fhand:
words = line.split() split the line into the word by using space for word in words: counts[word] = counts.get(word,0) + 1 set word to 0 by default and count word one each

lst = list() create the empty list for k,v in counts.items(): for k (key) and v(value) in counts that already set to items newtup = (v,k) new tuple equal (v,k) lst.append(newtup) append the newtup to the lst

lst = sorted(lst,reverse = True) sort the lst and reverse

for v,k in lst[:10]: for v and k in lst include only the first to 10 print(k,v) print the key and value


Question

  • Which does the same thing as the following code?:

      lst = []
      for key, val in counts.items():
          newtup = (val, key)
          lst.append(newtup)
      lst = sorted(lst, reverse=True)
      print(lst)
    
  • Ans

      print( sorted( [ (v,k) for k,v in counts.items() ], reverse=True ) )
    

Notes mentioning this note


ນີ້ຄືກຣາຟທີ່ລິ້ງໄປຫາທຸກໜ້າໃນ garden ນີ້ 🕸️.