如何使用列表中的键和 Python 中的空值初始化字典? [英] How to initialize a dict with keys from a list and empty value in Python?

查看:32
本文介绍了如何使用列表中的键和 Python 中的空值初始化字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从中得到:

keys = [1,2,3]

为此:

{1:无,2:无,3:无}

有pythonic的方法吗?

这是一种丑陋的方法:

<预><代码>>>>键 = [1,2,3]>>>dict([(1,2)]){1:2}>>>dict(zip(keys, [None]*len(keys))){1:无,2:无,3:无}

解决方案

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

这实际上是一个类方法,因此它也适用于 dict 子类(如 collections.defaultdict).可选的第二个参数指定用于键的值(默认为 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}

解决方案

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

这篇关于如何使用列表中的键和 Python 中的空值初始化字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆