Home > Software design >  Convert values-as-list of a dictionary to values-as-tuple (python)
Convert values-as-list of a dictionary to values-as-tuple (python)

Time:01-04

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

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?

CodePudding user response:

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')}
  •  Tags:  
  • Related