gpt4 book ai didi

Python 从具有键和多个值的字典构建元组

转载 作者:行者123 更新时间:2023-11-30 23:23:01 24 4
gpt4 key购买 nike

我正在尝试从字典构建元组,如下所示{key:值列表}。

def dictionary_tuples(key, values):
return dict((x.key, x.value) for x in values)

graph = {'11': ['12','40','41','10'], '100': ['120','400','410','100'], '12':['11','13'], '13':['12']}
a= '11'
b = graph['11']
dictionary_tuples(a,b)

而且它不起作用。我想要实现的是: [('11','12'), ('11','40'), ('11','41'), ('11','10')]

最佳答案

使用带有双循环的列表理解:

[(key, elem) for key, value in graph.items() for elem in value]

演示:

>>> graph = {'11': ['12','40','41','10'], '100': ['120','400','410','100'], '12':['11','13'], '13':['12']}
>>> [(key, elem) for key, value in graph.items() for elem in value]
[('11', '12'), ('11', '40'), ('11', '41'), ('11', '10'), ('100', '120'), ('100', '400'), ('100', '410'), ('100', '100'), ('12', '11'), ('12', '13'), ('13', '12')]

关于Python 从具有键和多个值的字典构建元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com