2

Is there an easy way to map/for-comprehend namedtuples like

[k + v for k,v in namedtuple]

I feel like I can write an easy map function for this using asDict but what about for comprehensions.

fuzzycuffs
  • 139
  • 1
  • 15

1 Answers1

1

We would have to know a little more about what the namedtuple data looks like to use list comprehension.

Alternatively, a broader method would be to use a recursive function to unpack nested data structures:

def reducer(obj):
    if isinstance(obj, dict):
        return {key: reducer(value) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [reducer(value) for value in obj]
    elif isnamedtupleinstance(obj):  # see note
        return {key: reducer(value) for key, value in obj._asdict().items()}
    elif isinstance(obj, tuple):
        return tuple(reducer(value) for value in obj)
    else:
        return obj

Note: If you're namedtuple contains other namedtuples you'll need this helper method to check for instances of namedtuples so they aren't mistaken for actual tuples:

def isnamedtupleinstance(x):
    _type = type(x)
    bases = _type.__bases__
    if len(bases) != 1 or bases[0] != tuple:
        return False
    fields = getattr(_type, '_fields', None)
    if not isinstance(fields, tuple):
        return False
    return all(type(i)==str for i in fields)
Community
  • 1
  • 1
brennan
  • 3,392
  • 24
  • 42