I have
x = {'a':set([1]) , 'b':set([2]), 'c':set([3]) }
It is guaranteed that there is only one element in the set. I need to convert this to
{'a': 1, 'c': 3, 'b': 2}
Following works:
x1 = {k:x[k].pop() for k in x.keys()} OR
x1 = {k:next(iter(x[k])) for k in x.keys()}
but I am not liking it as pop()
here is modifying the original collection. I need help on following.
functools.reduce
for this. 如果你想通过拆包来做到这一点,那就是
{k: item for k, [item] in x.iteritems()}
In my opinion, the most readable option would be to use next
and iter
.
Unpacking might also not be of much use since it is more of an assignment operation.
(See user2357112's answer)
How about simply:
>>> {k: next(iter(v)) for k, v in x.items()}
{'a': 1, 'c': 3, 'b': 2}
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.