当前位置: 动力学知识库 > 问答 > 编程问答 >

dictionary - How to initialize a dict with keys from a list and empty value in Python?

问题描述:

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}

网友答案:

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.)

网友答案:

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}
网友答案:
dict.fromkeys(keys, None)
网友答案:
>>> keyDict = {"a","b","c","d"}

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

Output:

{'a': [], 'c': [], 'b': [], 'd': []}
网友答案:
d = {}
for i in keys:
    d[i] = None
网友答案:
d = {}
for i in range(len(keys)):
    d.update({i+1:[]})
分享给朋友:
您可能感兴趣的文章:
随机阅读: