python建立字典读取键和值_在Python字典中动态创建键和值
在Python2中,我會做這樣的事情。。。在#! /usr/bin/env python
'''
Count vowels in a list of words & show a grand total
Words come from a plain text file with one word per line
'''
import sys
vowels = 'aeiouy'
def make_count_dict():
''' Create a dict for counting vowels with all values initialised to 0 '''
return dict(zip(vowels, (0,)*len(vowels)))
def get_counts(d):
return ' '.join('%2d' % d[k] for k in vowels)
def count_vowels(wordlist):
hline = '_'*45
print '%3s: %-20s: %s' % ('Num', 'Word', ' '.join('%2s' % v for v in vowels))
print hline
total_counts = make_count_dict()
for num, word in enumerate(wordlist, start=1):
word_counts = make_count_dict()
for ch in word.lower():
if ch in vowels:
word_counts[ch] += 1
total_counts[ch] += 1
print '%3d: %-20s: %s' % (num, word, get_counts(word_counts))
print hline
print '%-25s: %s' % ('Total', get_counts(total_counts))
def main():
fname = len(sys.argv) > 1 and sys.argv[1]
if fname:
try:
with open(fname, 'r') as f:
wordlist = f.read().splitlines()
except IOError:
print "Can't find file '%s'; aborting." % fname
exit(1)
else:
wordlist = ['Mississippi', 'California', 'Wisconsin']
count_vowels(wordlist)
if __name__ == '__main__':
main()
總結(jié)
以上是生活随笔為你收集整理的python建立字典读取键和值_在Python字典中动态创建键和值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 马云是如何说服孙正义投资的 其实孙正义早
- 下一篇: 清水源是私人企业么