Oct-26-2016, 09:57 PM
Hi,
I'm trying to initialise an object by passing a list of named tuples. I would like to build a dictionary.
the code that came as a result of a previous post is:
I'm trying to initialise an object by passing a list of named tuples. I would like to build a dictionary.
the code that came as a result of a previous post is:
#!/usr/bin/python3 from collections import namedtuple Edge = namedtuple("Edge", "v1 v2") V = [Edge(1,2), Edge(2,3), Edge(3,1), Edge(4,1), Edge(2,4), Edge(4,5)] Graph = {edge.v1: [] for edge in V} for edge in V: Graph[edge.v1].append(edge.v2) for x,y in Graph.items(): print(" {} {} ".format(x,y))I would now like to create a class and create a dictionary as part of __init__. Something like this:
#!/usr/bin/python3 from collections import namedtuple Edge = namedtuple("Edge", "v1 v2") class Graph: def __init__(self, *args): Graph = {edge.v1: [for edge in args] } if __name__ == "__main__": V = [Edge(1,2), Edge(2,3), Edge(3,1), Edge(4,1), Edge(2,4), Edge(4,5)] g = Graph(V) start = 1 end = 3I however get the following error:
Graph = {edge.v1: [for edge in args] } ^ SyntaxError: invalid syntaxHow can I therefore create a comprehension that creates a dictionary, based on a list of named tuples that appears as mapping of a key value pair, where the value is a list? Basically, it should appear as it does in the first snippet of code.