sorting - Printing a dictionary in python with n elements per line -


given .txt 200,000 lines of single words, need count how many times each letter appears first letter of word. have dictionary keys 'a' - 'z', counts assigned each of values. need print them out in form

a:10,978 b:7,890 c:12,201 d:9,562 e:6,008 f:7,095 g:5,660 (...) 

the dictionary prints this

[('a', 10898), ('b', 9950), ('c', 17045), ('d', 10675), ('e', 7421), ('f', 7138), ('g', 5998), ('h', 6619), ('i', 7128), ('j', 1505), ('k'... 

how remove brackets & parentheses , print 5 counts per line? also, after sorted dictionary keys, started printing key, value instead of key:value

def main():     file_name = open('dictionary.txt', 'r').readlines()     alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']     letter = {}     in alphabet:         letter[i]=0     n in letter:         p in file_name:             if p.startswith(n):                 letter[n] = letter[n]+1     letter = sorted(letter.items())     print(letter) main() 

you couuld use following:

it loops through list, groups 5 elements, prints in desired format.

in [15]:

letter = [('a', 10898), ('b', 9950), ('c', 17045), ('d', 10675), ('e', 7421), ('f', 7138), ('g', 5998), ('h', 6619), ('i', 7128), ('j', 1505)] 

replace print(letter) following:

for grp in range(0, len(letter), 5):     print(' '.join(elm[0] + ':' + '{:,}'.format(elm[1]) elm in letter[grp:grp+5]))     a:10,898 b:9,950 c:17,045 d:10,675 e:7,421 f:7,138 g:5,998 h:6,619 i:7,128 j:1,505 

Comments

Popular posts from this blog

node.js - How to mock a third-party api calls in the backend -

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -