python3 字典建立三种方式 字母顺序字典

字典的建立:

 

1.批量建立字典:

import string
dict ={key:0 for key in string.ascii_lowercase }

letter_count
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0}

2.简单建立:

dict = {}
dict = {'a':112,'b':1}

3.在for里面建立

        char = ['we','are','the']
        for i in char:
            if not dict.__contains__(i):
                dict[i] = 1

这里涉及一个字典键值是否已经存在的问题,使用dict.__contains__(key)可以查看是否还有键值key。如果没有,那么直接新建。即可从一个空字典逐个建立字典。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章