to_dict

New in Atfinity 17.

Description

to_dict builds a dictionary from selected attributes of an instance. The argument is a dictionary literal whose keys are the attribute names to read from the instance.

For each entry:

  • If only an attribute name is given (using the dictionary shorthand, e.g. first_name), the resulting dictionary uses the attribute name itself as the key.

  • If a value is given (e.g. first_name: 'givenName'), that value is used as the key in the resulting dictionary.

Attributes whose value is unknown (i.e. not set on the instance) are skipped and do not appear in the resulting dictionary.

Examples

p is Person
p.to_dict({first_name, last_name})
// => {'first_name': 'Thorben', 'last_name': 'Croisé'}

Renaming all keys:

p is Person
p.to_dict({first_name: 'givenName', last_name: 'familyName'})
// => {'givenName': 'Thorben', 'familyName': 'Croisé'}

Mixing shorthand and explicit renames:

p is Person
p.to_dict({first_name, last_name: 'familyName'})
// => {'first_name': 'Thorben', 'familyName': 'Croisé'}

To narrow down or rename keys of an existing dictionary (rather than building one from an instance), use pick.

Last updated

Was this helpful?