Dictionaries and Loops


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

code Example1

counts = dict()
print('Enter a line of text:')
line = input('')

words = line.split()

print('Words:' , words)

print('Counting...')
for word in words:
    counts[word] = counts.get(word,0) + 1
print ('Counts',counts)

output

Enter a line of text:
ທີ່ຈິງມັນອາດມີຫຼາຍເຫດຜົນທີ່ແຕກຕ່າງກັນສຳລັບແຕ່ລະຄົນທີ່ມີອາການ cringe ກັບຄຳຊົມທີ່ໄດ້ຮັບ ແຕ່ຂ້ອຍໄດ້ພົບ 5 ເຫດຜົນຫຼັກໆທີ່ເຮັດໃຫ້ຂ້ອຍ ເຈົ້າ ແລະພວກເຮົາ ຮູ້ສຶກແບບນີ້.

Words: ['ທີ່ຈິງມັນອາດມີຫຼາຍເຫດຜົນທີ່ແຕກຕ່າງກັນສຳລັບແຕ່ລະຄົນທີ່ມີອາການ', 'cringe', 'ກັບຄຳຊົມທີ່ໄດ້ຮັບ', 'ແຕ່ຂ້ອຍໄດ້ພົບ', '5', 'ເຫດຜົນຫຼັກໆທີ່ເຮັດໃຫ້ຂ້ອຍ', 'ເຈົ້າ', 'ແລະພວກເຮົາ', 'ຮູ້ສຶກແບບນີ້.']
Counting...
Counts {'ທີ່ຈິງມັນອາດມີຫຼາຍເຫດຜົນທີ່ແຕກຕ່າງກັນສຳລັບແຕ່ລະຄົນທີ່ມີອາການ': 1, 'cringe': 1, 'ກັບຄຳຊົມທີ່ໄດ້ຮັບ': 1, 'ແຕ່ຂ້ອຍໄດ້ພົບ': 1, '5': 1, 'ເຫດຜົນຫຼັກໆທີ່ເຮັດໃຫ້ຂ້ອຍ': 1, 'ເຈົ້າ': 1, 'ແລະພວກເຮົາ': 1, 'ຮູ້ສຶກແບບນີ້.': 1}



code Example2

count = {'chuk':1, 'yoyo': 12, 'jan': 100}
for key in count:
    print(key,count[key])

output

chuk 1
yoyo 12
jan 100


Code Example 3

jjj = {'chuk':1, 'yoyo': 12, 'jan': 100}
print(list(jjj))
print(jjj.keys())
print(jjj.values())
print(jjj.items())

Output

['chuk', 'yoyo', 'jan']
dict_keys(['chuk', 'yoyo', 'jan'])
dict_values([1, 12, 100])
dict_items([('chuk', 1), ('yoyo', 12), ('jan', 100)])


code Example 4

jjj = {'chuk':1, 'yoyo': 12, 'jan': 100}
print(list(jjj))
print(jjj.keys())
print(jjj.values())
for aaa,bbb in jjj.items():
    print (aaa,bbb)

Output

['chuk', 'yoyo', 'jan']
dict_keys(['chuk', 'yoyo', 'jan'])
dict_values([1, 12, 100])
chuk 1
yoyo 12
jan 100



code Example 5

name =input('Enter file name:')
handle = open (name)

counts =dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0 ) + 1

bigcount = None
bigword = None
for word,count in counts.items():
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count

print(bigword,bigcount)

Output

Enter file name:mbox.txt
Jan 352

question

  • What will the following code print?:

      counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
      for key in counts:
          if counts[key] > 10:
              print(key, counts[key])
    
  • Ans

      annie 42
      jan 100
    

Notes mentioning this note


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