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.
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()]
You can try this:
d = {"k1": ("v1"), "k2": ("v2"), "k3": ("v3")}
new_data = list(d.items())
Output:
[('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]
Here you go:
>>> d = {"k1": ("v1"), "k2": ("v2"), "k3": ("v3")}
>>> [(a,d[a]) for a in d]
[('k3', 'v3'), ('k2', 'v2'), ('k1', 'v1')]
Just index the string out of the tuple in your list comprehension, ie,
[(k, v[0]) for k, v in d.items()]
This gives
[('k3', 'v'), ('k2', 'v'), ('k1', 'v')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.