问题:如何在Python中使用列表中的键和空值初始化字典?

我想从中得到:

keys = [1,2,3]

对此:

{1: None, 2: None, 3: None}

有pythonic的方法吗?

这是一个丑陋的方法:

>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}

I’d like to get from this:

keys = [1,2,3]

to this:

{1: None, 2: None, 3: None}

Is there a pythonic way of doing it?

This is an ugly way to do it:

>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}

回答 0

dict.fromkeys([1, 2, 3, 4])

这实际上是一个类方法,因此它也适用于dict子类(如collections.defaultdict)。可选的第二个参数指定用于键的值(默认为)None

dict.fromkeys([1, 2, 3, 4])

This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict) as well. The optional second argument specifies the value to use for the keys (defaults to None.)


回答 1

没有人愿意提供字典理解的解决方案吗?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

nobody cared to give a dict-comprehension solution ?

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

回答 2

dict.fromkeys(keys, None)
dict.fromkeys(keys, None)

回答 3

>>> keyDict = {"a","b","c","d"}

>>> dict([(key, []) for key in keyDict])

输出:

{'a': [], 'c': [], 'b': [], 'd': []}
>>> keyDict = {"a","b","c","d"}

>>> dict([(key, []) for key in keyDict])

Output:

{'a': [], 'c': [], 'b': [], 'd': []}

回答 4

d = {}
for i in keys:
    d[i] = None
d = {}
for i in keys:
    d[i] = None

回答 5

许多地方要附加任意键默认/初始值的工作流程,你没有需要到哈希每个键单独的时间提前。您可以使用collections.defaultdict。例如:

from collections import defaultdict

d = defaultdict(lambda: None)

print(d[1])  # None
print(d[2])  # None
print(d[3])  # None

这样效率更高,它省去了在实例化时散列所有键的麻烦。此外,defaultdict是的子类dict,因此通常无需转换回常规字典。

对于需要对许可键进行控制的工作流,可以dict.fromkeys按照已接受的答案使用:

d = dict.fromkeys([1, 2, 3, 4])

In many workflows where you want to attach a default / initial value for arbitrary keys, you don’t need to hash each key individually ahead of time. You can use collections.defaultdict. For example:

from collections import defaultdict

d = defaultdict(lambda: None)

print(d[1])  # None
print(d[2])  # None
print(d[3])  # None

This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict is a subclass of dict, so there’s usually no need to convert back to a regular dictionary.

For workflows where you require controls on permissible keys, you can use dict.fromkeys as per the accepted answer:

d = dict.fromkeys([1, 2, 3, 4])

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。