python - 如何从元组列表形成字典?

标签 python list dictionary tuples key-value-coding

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

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

我想制作一本看起来像这样的字典:

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

所以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}

谁能告诉我我的逻辑到底错在哪里以及我应该如何进一步进行?

最佳答案

iDict 不会成为一本字典。不能,因为按键是重复的。根据定义,字典具有唯一的键。相反,我猜测您确实希望 iDict 成为字典的 list,其中包含 'FirstParam''SecondParam' 的每种组合。 code> 表示为字典之一。

首先,我们要将元组列表分成两个列表,一个包含所有 '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']

现在我们需要将这两个列表的每个组合并从中形成一个字典,然后将这些字典放入一个列表中。我们可以使用 itertools.product 在一条语句中完成所有这些操作。获取所有参数组合,使用 dictproduct 返回的元组转换为字典,并对所有带有 list comprehension 的组合执行此操作.

from itertools import product

result = [dict(tup) for tup in product(first_params, second_params)]

print(result)
# [{'FirstParam': 1, 'SecondParam': 5},
#  {'FirstParam': 1, 'SecondParam': 6},
#  {'FirstParam': 1, 'SecondParam': 7},
#  {'FirstParam': 2, 'SecondParam': 5},
#  {'FirstParam': 2, 'SecondParam': 6},
#  {'FirstParam': 2, 'SecondParam': 7},
#  {'FirstParam': 3, 'SecondParam': 5},
#  {'FirstParam': 3, 'SecondParam': 6},
#  {'FirstParam': 3, 'SecondParam': 7},
#  {'FirstParam': 4, 'SecondParam': 5},
#  {'FirstParam': 4, 'SecondParam': 6},
#  {'FirstParam': 4, 'SecondParam': 7}]

关于python - 如何从元组列表形成字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433602/

相关文章:

python - "error reading PNG header"运行时错误

带有字符串索引的 Python 数组

python - python 中的汉诺塔与 turtle 图形移动磁盘

python - 为什么 random.shuffle(list(range(n))) 有效,但 random.shuffle(range(n)) 无效?

C# 确定字典中的值

python - Scrapy:合并来自不同站点的项目

python - 如何从 Python 链接下载扩展名为 .torrent 的文件

python - 如何让opcua在python中更加高效?

python字典插入到mysql

c++ - 重新分配 std::map::value_type& 是否安全?