在python 2.6中创建字典词典 [英] Creating dictionary of dictionaries in python 2.6

查看:77
本文介绍了在python 2.6中创建字典词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python2.7中有一行代码,该代码生成一个空字典的字典:

I have a line of code in python2.7 that generates a dictionary of empty dictionaries:

values=[0,1,2,4,5,8] 
value_dicts={x:{} for x in values}

在python2.6上运行时会引发语法错误.

which throws a syntax error when run on python2.6.

我可以使用for循环做同样的事情:

I can do the same thing using a for loop:

values_dicts={}
values=[0,1,2,4,5,8]
for value in values :
values_dicts[value]={}
values_dicts
Out[25]: {0: {}, 1: {}, 2: {}, 4: {}, 5: {}, 8: {}}

但这似乎很愚蠢.为什么列表理解(在第一个块中)在python2.6中不起作用?

But that seems silly. Why does the list comprehension (in the first block) not work in python2.6?

推荐答案

您可以使用dict()构造函数:

value_dicts = dict((x, {}) for x in values)

这使用生成器表达式构造(key, value)元组,dict()构造函数很乐意为您将其变成字典.

This uses a generator expression that constructs (key, value) tuples, which the dict() constructor is happy to turn into a dictionary for you.

演示:

>>> values=[0,1,2,4,5,8] 
>>> dict((x, {}) for x in values)
{0: {}, 1: {}, 2: {}, 4: {}, 5: {}, 8: {}}

直到Python 2.7和Python 3才引入您使用的语法(字典理解),请参见

The syntax you used (a dict comprehension) was not introduced until Python 2.7 and Python 3, see PEP 274.

这篇关于在python 2.6中创建字典词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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