簡介
Python 字典(Dictionary) fromkeys() 函數用於創建一個新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對應的初始值。
語法
fromkeys()方法語法:
dict.fromkeys(seq[, value])
參數
- seq -- 字典鍵值列表
- value -- 可選參數, 設置鍵序列(seq)的值
返回值
該方法返回列表。
實例一:展示了 fromkeys()函數的使用方法:
#!/usr/bin/python seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) #不賦值 print "New Dictionary : %s" % str(dict) #賦值10 dict = dict.fromkeys(seq, 10) print "New Dictionary : %s" % str(dict) #輸出結果: New Dictionary : {'age': None, 'name': None, 'sex': None} New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
實例二:請統計字符串in_str里面每個元音字母各出現了多少次
# string of vowels vowels = 'aeiou' counter = {}.fromkeys(vowels,0) # change this value for a different result in_str = 'Hello, have you tried our turorial section yet?' # make it suitable for caseless comparisions in_str = in_str.casefold() # make a dictionary with each vowel a key and value 0 # count the vowels for char in in_str: if char in counter: counter[char] += 1 print(counter)
#輸出結果
{'a': 2, 'e': 5, 'i': 3, 'o': 5, 'u': 3}