New Upload weather data from web services into TM1/Planning Analytics — Read the post →

Working with Python Data Structures in a TM1 Context

Lists and dictionaries are probably the most important data structures that you should be aware of when writing Python scripts for your IBM TM1 and Planning Analytics application.

Lists: an ordered collection of items

A list is a data structure that holds an ordered collection of items:

A list in Python has lots of useful features:

Function

Example

Definition

append

fruits.append('dragonfruit')

Adding a new item

healthy_stuff = fruits + vegetables

Concatenating two lists

len()

len(healthy_stuff)

Getting the number of items

It is also very easy to loop through the list:

In Python when you want to create a new list from an existing one, it can be done easily through List Comprehension. The code almost reads like plain English.

Lists in a TM1 context

Python lists can be used to manipulate elements. For example, create a list containing all elements from a hierarchy:

Once created, you can leverage list properties:

Function

Example

Definition

len()

len(element_names)

Getting the number of elements

in

'NYC' in element_names

Checking if an element exists

Dictionaries

A dictionary is like an address-book where you associate keys (name) with values (details). The key of each object must be unique:

Function

Example

Definition

[]

food_rating["Xiao Long Bao"] = 5

Adding a new element

get()

food_rating.get("Bacon")

Getting the value of an object

sum()/len()

sum(food_rating.values()) / len(food_rating)

Calculating average

del

del food_rating['Ice Cream']

Removing one object

Dictionaries in TM1 context

Python dictionaries can be used to manipulate TM1 data. Create a dictionary from an MDX statement:

Use execute_mdx_rows_and_values to create a dictionary with cell coordinates as keys and values as values:

Loop through and print each intersection and value:

To get a specific value, specify all coordinates:

Note that 'Chicago' or 'CHI CAGO' return the same value because the TM1py dictionary is case and space insensitive.

More examples are available in the data_structures_in_python.ipynb Jupyter Notebook in the TM1py samples repository on GitHub.