fromkeys是創造一個新的字典。就是事先造好一個空字典和一個列表,fromkeys會接收兩個參數,第一個參數為從外部傳入的可迭代對象,會將循環取出元素作為字典的key值,另外一個參數是字典的value值,不寫所有的key值所對應的value值均為None,寫了則為默認的值
fromkeys() 方法語法
dict.fromkeys(seq[, value])
seq -- 字典鍵值列表。
value -- 可選參數, 設置鍵序列(seq)對應的值,默認為 None。
先看個簡單的實例:
1 v = dict.fromkeys(range(10)) 2 print(v) 3 4 結果: 5 {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
傳入第二個參數:
1 v = dict.fromkeys(range(10),'hello') 2 print(v) 3 4 結果: 5 {0: 'hello', 1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello', 5: 'hello', 6: 'hello', 7: 'hello', 8: 'hello', 9: 'hello'}
再看一個實例:
1 # dict.fromkeys(seq[, value]) 2 seq = ('name', 'age', 'class') 3 4 # 不指定值 5 dict = dict.fromkeys(seq) 6 print("新的字典為 : %s" % str(dict)) 7 8 # 賦值 10 9 dict = dict.fromkeys(seq, 10) 10 print("新的字典為 : %s" % str(dict)) 11 >>新的字典為 : {'age': None, 'name': None, 'class': None} 12 13 # 賦值一個元組 14 dict = dict.fromkeys(seq,('zs',8,'Two')) 15 print("新的字典為 : %s" % str(dict)) 16 >>新的字典為 : {'age': ('zs', 8, 'Two'), 'name': ('zs', 8, 'Two'), 'class': ('zs', 8, 'Two')}