[英]Creating a Simple Dictionary from a List
很抱歉問一個簡單的問題:
我有以下清單:
x = ["one", "two", "three" ]
創建此字典的最佳方法是什么:
{"one":1, "two":1, "three":1 }
謝謝
使用字典理解 :
{key: 1 for key in x}
print dict.fromkeys(["one","two","three"],1)
我會怎么做...如果您真的只是想從列表中做出決定(也許可以加快搜索速度)
如果您不在乎價值是什么,就可以做
print dict.fromkeys(["one","two","three"])
這將是默認的None
這具有為python <2.7工作的額外好處,而且很容易告訴您您在做什么,因為dict理解總是讓我想到set理解
我將推斷出您正在尋找一個Counter :
>>> from collections import Counter
>>> x = ["one", "two", "three" ]
>>> Counter(x)
Counter({'three': 1, 'two': 1, 'one': 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.