0

I am trying to add a new property to a named tuple in which I want to store some values. Post that I want to convert it back to JSON to pass it as a parameter in api. I found an answer to add a property to a namedTuple however it creates a type and doesn't modify the instance itself. What is the best way to achieve above functionality.

how do I add fields to a namedtuple?

def _json_object_hook(d): 
    return namedtuple('X', d.keys())(*d.values())
def json2obj(data):
    return json.loads(data, object_hook=_json_object_hook)

def lambda_handler(event, context):
    registrationResponse = s3.get_object(Bucket=bucket, Key=registrationkey)
    registrationResponse = registrationResponse['Body'].read().decode('utf-8')
    registration = json2obj(registrationResponse)   
    abc = namedtuple('registration',registration._fields+('point',))
    y = abc._asdict()  # TypeError: _asdict() missing 1 required positional argument: 'self'

On debugger

type(abc) #<class 'type'>
type(registration) #<class '__main__.X'>    
registration #<X, len() = 7>    
abc #<class '__main__.registration'>
Shantanu Gupta
  • 20,688
  • 54
  • 182
  • 286

1 Answers1

0

namedtuple does not create a namedtuple. It creates a class you should then instantiate:

Record = namedtuple('Record', "a b")

If you have data in a dict like,

d1 = dict(a=1, b=2)

You can instantiate a similar record from it with:

r1 = Record(**d1)

Do not change namedtuple fields because, like tuples, they are supposed to be immutable.

In alternative add/change dict keys, build a new Record class based in its keys and instantiate the namedtuple from the dict, to access through field names.

progmatico
  • 4,714
  • 1
  • 16
  • 27