Python Forum

Full Version: Transforming nested key-tuples into their dictionary values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Surely there has got to be a better way of doing this?


>>> d = dict(enumerate(list('abcde')))
>>> INPUT = [[(0, 1, 2), (3, 4)], [(0, 1, 3), (2, 4)], [(0, 1, 4), (2, 3)], [(0, 2, 3), 
(1, 4)], [(0, 2, 4), (1, 3)], [(0, 3, 4), (1, 2)], [(1, 2, 3), (0, 4)], [(1, 2, 4), (0, 3)], 
[(1, 3, 4), (0, 2)], [(2, 3, 4), (0, 1)]]
>>> list(map(lambda grouping: tuple(map(lambda group: tuple(map(lambda id_: d[id_], group)), grouping)), INPUT))
Output:
[(('a', 'b', 'c'), ('d', 'e')), (('a', 'b', 'd'), ('c', 'e')), (('a', 'b', 'e'), ('c', 'd')), (('a', 'c', 'd'), ('b', 'e')), (('a', 'c', 'e'), ('b', 'd')), (('a', 'd', 'e'), ('b', 'c')), (('b', 'c', 'd'), ('a', 'e')), (('b', 'c', 'e'), ('a', 'd')), (('b', 'd', 'e'), ('a', 'c')), (('c', 'd', 'e'), ('a', 'b'))]
even without going into understanding your goal - instead of 3 lamdas - define separarte functions... oneliners are not always better coding
In what way do you want it to be "better"? Run faster, clearer code, different output, something else?
My goal is to substitute the keys in the input object with their corresponding dictionary value. I want to write clearer code or faster code (or both). In particular, I'm wondering if there is no more standard way of doing what I'm doing -- for example, if there is some function I can import.
No, there's no obvious mapping function that does mapping within nested structures natively. I'd probably write it as separate loops to improve readability if the performance weren't critical.