create dictionary from **kwargs that include tuple - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: create dictionary from **kwargs that include tuple (/thread-651.html) |
create dictionary from **kwargs that include tuple - bluefrog - Oct-26-2016 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 = 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. RE: create dictionary from **kwargs that include tuple - Yoriz - Oct-26-2016 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 RE: create dictionary from **kwargs that include tuple - Larz60+ - Oct-26-2016 Hello, I do exactly this in some code that I just posted on github today https://github.com/Larz60p/NLTK-Corpora-Catalog/blob/master/CorporaData.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} |