简体   繁体   English

从列表创建简单字典

[英]Creating a Simple Dictionary from a List

Sorry for asking a simple question: 很抱歉问一个简单的问题:

I have the following list: 我有以下清单:

 x = ["one", "two", "three" ]

What is the best way to create this dictionary: 创建此字典的最佳方法是什么:

 {"one":1, "two":1, "three":1 }

Thanks 谢谢

使用字典理解

{key: 1 for key in x}
print dict.fromkeys(["one","two","three"],1)

Is how I would do it ... if you really just want to make a dict from a list (to speed up searches maybe) 我会怎么做...如果您真的只是想从列表中做出决定(也许可以加快搜索速度)

if you dont care what the value is you can just do 如果您不在乎价值是什么,就可以做

print dict.fromkeys(["one","two","three"])

and it will be the default None 这将是默认的None

this has the added benefit of working for python < 2.7 plus it is very easy to tell what you are doing , where as dict comprehensions always make me think of set comprehensions 这具有为python <2.7工作的额外好处,而且很容易告诉您您在做什么,因为dict理解总是让我想到set理解

I'm going to extrapolate and guess that you're looking for a Counter : 我将推断出您正在寻找一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM