Python使用键和多个值从字典构建元组

时间:2014-06-12 14:42:56

标签: python dictionary tuples

我试图从字典中构建一个类似于{key:values of values}的元组。

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')]

3 个答案:

答案 0 :(得分:3)

使用带双循环的列表推导:

[(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')]

答案 1 :(得分:1)

您可以使用以下功能传递图表

def dictionary_tuples(key, values):
    return [(key, item) for item in values[key]]

因此:

>>> def dictionary_tuples(key, values):
...     return [(key, item) for item in values[key]]
... 
>>> 
>>> dictionary_tuples(a, graph)
[('11', '12'), ('11', '40'), ('11', '41'), ('11', '10')]
>>> 

或者,如果您只想传递节点:

def dictionary_tuples(key, values):
    return [(key, item) for item in values]

因此:

>>> def dictionary_tuples(key, values):
...     return [(key, item) for item in values]
... 
>>> graph = {'11': ['12','40','41','10'], '100': ['120','400','410','100'], '12':['11','13'], '13':['12']}
>>> a= '11'
>>> b = graph[a]
>>> dictionary_tuples(a, b)
[('11', '12'), ('11', '40'), ('11', '41'), ('11', '10')]
>>> 

答案 2 :(得分:-1)

正如我所说,您需要一个列表作为输出,因此您需要使用以下内容更改代码:

def dictionary_tuples(key, values):
    return list((key, value) for value in values)

给出:

print dictionary_tuples(a,b)
[('11', '12'), ('11', '40'), ('11', '41'), ('11', '10')]