Python Forum

Full Version: Dictionary and tuples list comprehensions help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
tuples_list = [k + (v,) for k, v in Dictionary.items()]
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)]