attributes Property (Python)

The attributes property of a Variable object gets or sets custom variable attributes. It can also be used to clear any custom attributes. The attributes property behaves like a Python dictionary in terms of getting, setting, and deleting values. A Python dictionary consists of a set of keys, each of which has an associated value that can be accessed simply by specifying the key. In the case of variable attributes, each key is the name of an attribute and the associated value is the value of the attribute, which can be a single value or a list or tuple of values. A list or tuple of values specifies an attribute array.

  • When setting attributes, attribute names and values must be given as quoted strings.

Retrieving Variable Attributes. You retrieve custom variable attributes for a specified variable from the attributes property of the associated Variable object. You retrieve the value of a particular attribute by specifying the attribute name, as in:

varObj = datasetObj.varlist['gender']
attrValue = varObj.attributes['attrName']

Attribute values are always returned as a tuple.

You can iterate through the set of variable attributes using the data property, as in:

varObj = datasetObj.varlist['gender']
for attrName, attrValue in varObj.attributes.data.iteritems():
   print attrName, attrValue

Adding and Modifying Attributes. You can add new attributes and modify values of existing ones. For example:

varObj = datasetObj.varlist['age']
varObj.attributes['AnswerFormat'] = 'Fill-in'
  • If the attribute AnswerFormat exists, its value is updated to 'Fill-in'. If the attribute AnswerFormat doesn't exist, it is added to any existing ones for the variable age.

Resetting Attributes. You can reset the attributes to a new specified set. For example:

varObj = datasetObj.varlist['gender']
varObj.attributes = {'DemographicVars':'1','Binary':'Yes'}
  • You reset the attributes by setting the attributes property to a new Python dictionary. Any existing attributes for the variable are cleared and replaced with the specified set.

Deleting Attributes. You can delete a particular attribute or the entire set of attributes for a specified variable. For example:

varObj = datasetObj.varlist['gender']
#Delete the attribute Binary
del varObj.attributes['Binary']
#Delete all attributes
del varObj.attributes