任意命名词典

时间:2016-06-08 23:33:02

标签: list python-2.7 dictionary

我有list=[gender,employment type],我想创建一个名为gender的字典和另一个名为employment type的字典。我可以将我的词典命名如下:

> list[0] = {key1: value}
> list[1] = {key2: value}

我想根据某些输入任意命名我的字典。是否可以使用列表中的字符串值声明字典?

1 个答案:

答案 0 :(得分:0)

您可能希望查看mapenumerate的组合。由于您的标记,我已经链接到2.x文档,但我相信3.x中的函数几乎相同。

使用地图:

>>> list=["gender", "employment type"]
>>> mapped=map(lambda x: {"key":x})
[{'key': 'gender'}, {'key': 'employment type'}]

枚举:

>>> list=["gender", "employment type"]
>>> map(lambda (i, x): {"key"+str(i):x}, enumerate(list))
[{'key0': 'gender'}, {'key1': 'employment type'}]

给定更深层嵌套的结构 - 类似于list=[[gender], [employment type]] - 您可以将更复杂的函数定义为映射器。

或者,如果您正在查看[gender, employment type]元组的数组(更接近[(gender, employment type)]的某些元素) - 您可能希望查看“解压缩”数据。请参阅SO问题:A Transpose/Unzip Function in Python (inverse of zip)

相关问题