Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Union over iterable elements in set comprehension

I have a list of unique keys and I want to find the unique character set used to compose those keys

idx_keys = [
    "1996/a/50/18_supp__323:5",
    "1996/a/50/18_supp__326:1",
    "1996/a/50/18_supp__368:2",
    "1996/a/50/18_supp__907:1",
    "1996/a/c_2/51/sr_37_164:1",
]

I can do this

chars = set()
for k in idx_keys:
    chars = chars.union(k)

print(chars)
print(f"{'-' in chars = }")  # -> False
print(f"{'_' in chars = }")  # -> True

But I can’t do this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print({set(k) for chars in idx_keys}) # -> TypeError: unhashable type: 'set'

Can someone explain how I can do this more neatly. Obviously the logic here applies to getting the union of any nested iterable, not just a list of strings.

Caveat: I know doing this inside a set comprehension may not be ideal from a readability perspective, but humor me. I think I saw something similar with the walrus operator and would like to see what a compact solution looks like, also because it might be faster.

>Solution :

You can use functools.reduce and operator.or_ to achieve a similar result:

from functools import reduce
import operator as op

chars = reduce(op.or_, map(set, idx_keys))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading