![]() |
Dictionary and tuples list comprehensions help - 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: Dictionary and tuples list comprehensions help (/thread-22849.html) |
Dictionary and tuples list comprehensions help - paul41 - Nov-29-2019 Hi I have a dictionary with keys and values and I am wanting to convert these into a list of tuples. Dictionary = {'(A,B):1,'(C,D)':2} Note that the keys are currently tuples. I basically want to add the value to the key tuples to form the following format: TuplesList = [(A,B,1), (C,D,2)] I have made an attempt at doing this using the following; TuplesList = [k,v) for k, v in Dictionary.items()] However, this is giving me the incorrect output of; TuplesList = [(('A','B'),1),(('C','D'),2)] Any advice would be appreciated on how I can get my desired output. Thank you RE: Dictionary and tuples list comprehensions help - ichabod801 - Nov-29-2019 tuples_list = [k + (v,) for k, v in Dictionary.items()] RE: Dictionary and tuples list comprehensions help - perfringo - Nov-29-2019 Desired output with tuple unpacking: >>> d = {('spam', 'ham'): 1, ('eggs', 'bacon'): 2} >>> [(*k, v) for k, v in d.items()] [('spam', 'ham', 1), ('eggs', 'bacon', 2)] |