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

Convert values-as-list of a dictionary to values-as-tuple (python)

Consider a dictionary:
{'a': ['b', 'c'], 'b':['a', 'c', 'e'], 'c':['a', 'b', 'f']}

How can I get the values as tuple in one line:
{'a': ('b', 'c'), 'b':('a', 'c', 'e'), 'c':('a', 'b', 'f')}


First I converted the values of this dictionary to list of tuple using comprehension

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

list_of_tuple = [tuple(val) for val in dict.values()]

Iterating over the values of dict and items in list_of_tuple, then equating nth element of dict to nth element of list_of_tuple doesn’t work.

Is there a better, compact way of doing this?

>Solution :

You can use a dict comprehension:

out = {k:tuple(v) for k,v in d.items()}

or map with lambda:

out = dict(map(lambda x: (x[0],tuple(x[1])), d.items()))

or map with zip:

out = dict(zip(d.keys(), map(tuple, d.values())))

Output:

{'a': ('b', 'c'), 'b':('a', 'c', 'e'), 'c':('a', 'b', 'f')}
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