Python Forum
Transforming nested key-tuples into their dictionary values - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Transforming nested key-tuples into their dictionary values (/thread-25756.html)



Transforming nested key-tuples into their dictionary values - ClassicalSoul - Apr-11-2020

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'))]



RE: Transforming nested key-tuples into their dictionary values - buran - Apr-11-2020

even without going into understanding your goal - instead of 3 lamdas - define separarte functions... oneliners are not always better coding


RE: Transforming nested key-tuples into their dictionary values - bowlofred - Apr-11-2020

In what way do you want it to be "better"? Run faster, clearer code, different output, something else?


RE: Transforming nested key-tuples into their dictionary values - ClassicalSoul - Apr-11-2020

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.


RE: Transforming nested key-tuples into their dictionary values - bowlofred - Apr-11-2020

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.