Search code examples
pythonpython-3.xdictionarytuplesdata-conversion

How to convert dictionary key-value pairs to tuples


Must convert this:

d = {"k1": ("v1"), "k2": ("v2"), "k3": ("v3")}

to this:

[('k1, v1'), ('k2, v2'), ('k2, v3')]

I tried this:

[(k, v) for k, v in d.items()]

But got this:

[('k1', ('v1')), ('k2', ('v2')), ('k3', ('v3'))]

Close, but I cannot have those extra parentheses.


Solution

  • d = {"k1": ("v1"), "k2": ("v2"), "k3": ("v3")}
    print [(k, v) for k, v in d.items()]
    

    Already returns

    [('k3', 'v3'), ('k2', 'v2'), ('k1', 'v1')]
    

    (which is the same as actually doing list(d.items()))


    Now, if your dictionary is actually

    d = {"k1": ("v1",), "k2": ("v2",), "k3": ("v3",)}
    

    then that would explain your output. In this case, you need to do

    print [(k, v[0]) for k, v in d.items()]