如何从元组列表组成字典?

2024-05-18 06:33:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,例如:

iList = [('FirstParam', 1), ('FirstParam', 2), ('FirstParam', 3), ('FirstParam', 4), ('SecondParam', 5), ('SecondParam', 6), ('SecondParam', 7)]

我想做一本字典,它应该看起来像:

^{pr2}$

因此iDict构成了iList中所有可能的组合。在

MyExp将是我要形成的字典的键。因此,它最终应该是

Dictionary = dict(itertools.izip(MyExp, iDict))

我想先生成iDict

h = {}
[h.update({k:v}) for k,v in iList]
print "Partial:", h

我希望

Partial: {{'FirstParam': 1}, {'FirstParam': 2}, {'FirstParam': 3}, {'FirstParam': 4}{'SecondParam': 5}, {'SecondParam': 6}, {'SecondParam': 7}}

从这里我可以继续得到实际的iDict,然后Dictionary。 但是我得到了以下输出。在

Partial: {'FirstParam': 4, 'SecondParam': 7}

有谁能告诉我我的逻辑到底哪里出了问题,我该如何继续下去?在


Tags: 列表dictionary字典updatepartialdict元组itertools
2条回答

iDict不是一本字典。不能,因为钥匙是重复的。根据定义,字典有唯一的键。相反,我将猜测您真的希望iDict成为一个list的字典,其中'FirstParam'和{}的每一个组合都表示为一个字典。在

首先,我们将把元组列表分成两个列表,一个包含所有'FirstParam'元组,另一个包含所有'SecondParam'元组。在

iList = [('FirstParam', 1), ('FirstParam', 2), 
         ('FirstParam', 3), ('FirstParam', 4), 
         ('SecondParam', 5), ('SecondParam', 6), 
         ('SecondParam', 7)]

first_params = [i for i in iList if i[0] == 'FirstParam']
second_params = [i for i in iList if i[0] == 'SecondParam']

现在我们需要把这两个列表的每一个组合都取出来组成一个字典,然后把这些字典放到一个列表中。我们可以在一个语句中完成所有这些,使用^{}获取参数的所有组合,使用^{}product返回的元组转换为字典,并使用list comprehension对所有组合执行此操作。在

^{pr2}$

不幸的是,不能把thay放在一个大的听写式中,因为字典中不能有重复的键(而且会有多个“FirstParam”和“SecondParam”键)。如果要创建一个迷你字典列表(每个小字典的键为“FirstParam”和“SecondParam”),则:

iList = [('FirstParam', 1), ('FirstParam', 2), ('FirstParam', 3), ('FirstParam', 4), ('SecondParam', 5), ('SecondParam', 6), ('SecondParam', 7)]

first_params = [] #list for collecting all first params
second_params = [] #list for collecting all second params

#Assuming tuple is all first params and then all second params, can only loop through once (more efficient)
i = 0;
while(i < len(iList) and iList[i][0] == 'FirstParam'):
    first_params.append(iList[i])
    i+= 1
while(i < len(iList) and iList[i][0] == 'SecondParam'):
    second_params.append(iList[i])
    i+= 1

#Add to the final list of dictionaries
listOfParamDictionaries = []
for i in range(0, min(len(first_params), len(second_params))):
    listOfParamDictionaries.append({first_params[i][0] : first_params[i][1], second_params[i][0] : second_params[i][1]})

相关问题 更多 >