Python Forum

Full Version: create dictionary from **kwargs that include tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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:
#!/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 = 3
I however get the following error:
    Graph = {edge.v1: [for edge in args] }
                         ^
SyntaxError: invalid syntax
How 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.
Graph = {edge.v1: [for edge in args] }
in the 2nd code is not the same as
Graph = {edge.v1: [] for edge in V}
in the first code
Hello,

I do exactly this in some code that I just posted on github today https://github.com/Larz60p/NLTK-Corpora-...oraData.py

There is a good example in fluent python (Luciano Ramalho - O'Reilly page 70)

from collections import defaultdict
DIAL_CODES = [(86, 'China'), (91, 'India'), (1, 'United States') ...]

country_code = {country: code for code, country in DIAL_CODES}
so in your case,
from collections import defaultdict

V = [('v1', (1,2)), ('v2', (2,3)), ('v3', (3,1)), ('v4', (4,1)), ('v5', (2,4)), ('v6', (4,5))]

Graph = {edge: tup for edge, tup in  V}