2016-06-08 84 views
0

我有list=[gender,employment type],我想創建一個名爲gender的字典和另一個名爲employment type的字典。我能說出我的字典的東西如下:任意命名字典

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

我想說出我的字典任意取決於某些input.Is它宣佈使用從列表中的字符串值的字典可能嗎?

+0

你是不是指'{key1:value}'? – SethMMorton

+0

是,那裏,編輯 –

+0

你能澄清你想要什麼嗎?你寫的是合法的,但也許它不是你想要的。 – SethMMorton

回答

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)