0

I have some nested list and/or tuple structure, e.g.:

x = [('foo',), ('bar', 'baz'), ('Ni!', 'Peng!', 'Nee-wom!')]

If I also have a dictionary whose keys include the lowest-level elements of that nested structure, e.g.:

d = {'foo': 99, 'bar': 50, 'baz': 100, 'Ni!': 1, 'Peng!': 2, 'Nee-wom!': 5}

Is there an easy way to produce a new object that retains the original nesting structure but has the values from the original replaced per the dict? e.g.:

y = func(x, d)
y
# [(99,), (50, 100), (1, 2, 5)]

What is the func needed here?

This is basically a find and replace operation based on the dictionary, but preserving the structure. I know how to flatten a nested structure but am not sure that's the right approach or how to reproduce it after. Maybe I'm way overthinking it...

TY Lim
  • 509
  • 1
  • 3
  • 11

1 Answers1

4

Using a 2 level list comprehension:

y = [tuple(d[z] for z in y) for y in x]
print(y)

A function would be better:

def func(x,d):
    return [tuple(d[z] for z in y) for y in x]

y = func(x, d)
print(y)
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 1
    Change `tuple` to `type(y)` if you might have some other collection type nested (`set`, `list`, `bytes`) and want to preserve that type. To be clear, perfectly fine as is for OP's case, just mentioning ways to make it more general. – ShadowRanger Dec 08 '20 at 16:27
  • That works for the example shown, but is there a generalizable version? In particular, for two possible scenarios - 1) if not all the nesting is tuples (e.g. a mix of tuples and lists), and 2) if the number of nesting levels is variable e.g. if some of the elements of `x` have further nesting? – TY Lim Dec 08 '20 at 16:28
  • I see @ShadowRanger has answered (1), thanks! what about for the multiple nesting possibility? – TY Lim Dec 08 '20 at 16:30
  • Thanks @WasifHasan, but making it a function doesn't actually help with the possibility of further or variable nesting depths does it? – TY Lim Dec 08 '20 at 16:35