Python - 根據列表建立字典
當需要根據列表建立字典時,請使用“dict”方法中的“fromkeys”方法。
例子
以下是同樣的演示 -
my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)
my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)輸出
The list is
['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}說明
定義一個字串列表並將其顯示在控制檯上。
使用“dict”中提供的“fromkeys”方法將列表中的元素轉換為字典鍵。
每個鍵的值在此處指定。
這被分配給一個變數。
它在控制檯上作為輸出顯示。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP