如何仅使用python中的键初始化字典

时间:2019-04-10 14:28:18

标签: python dictionary

当我只有键而不是值时,我想在python中初始化字典-值将在代码后面出现。

我打算做这样的事情:

dict = {}
for key in key_list:
    dict[key] = None

问题是这是否是解决此问题的好方法,或者您有更好的建议?

3 个答案:

答案 0 :(得分:3)

您可以使用fromkeys方法执行此操作:

# As noted in comments, fromkeys is a staticmethod on the dict class and will return a dict instance
d = dict.fromkeys(list(range(10)))

d
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}

要更直接地解决这一点:

list_of_keys = ['o1', 'o2']

d = dict.fromkeys(list_of_keys)
{'o1': None, 'o2': None}

答案 1 :(得分:1)

如果您的密钥已经在内存中(假定为可迭代对象),则:

d = {key:None for key in keys}

与您发布的代码相同,只是简明扼要。

答案 2 :(得分:0)

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

您可以尝试该类方法。