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

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

问题描述

我想从这里获得:

  keys = [1,2,3] 

到:

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

是否有一个pythonic的做法这是一个丑陋的做法:





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


解决方案

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

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


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中的空值初始化dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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