Search code examples
pythonpython-2.7dictionaryiterable-unpackingfunctools

How to reduce the sets in dict values using comprehension?


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.

  • How can I use unpacking as mentioned here within comprehension.
  • Is there any way, I can use functools.reduce for this.
  • What can be a better or Pythonic way of doing this overall?

Solution

  • If you want to do this with an unpacking, that'd be

    {k: item for k, [item] in x.iteritems()}