print dict

Product:

Python 3.12
Planning Analytics 2.0.9.19

Microsoft Windows 2019 server

Install Python, and tm1py.  https://code.cubewise.com/blog/installing-tm1py/

Issue:

How get a value from a dict object in python?

This code part will list the servers on localhost (from the tm1py utils lib)

(you need to adjust the code to make the things you want)

 

import csv

import http.client as http_client

import json

import ssl

from enum import Enum, unique

from io import StringIO

from typing import Any, Dict, List, Tuple, Iterable, Optional, Generator, Union, Callable

from urllib.parse import unquote

import os

import sys

from datetime import datetime

from TM1py.Services import TM1Service

import requests

from mdxpy import MdxBuilder, Member

from requests.adapters import HTTPAdapter

from TM1py.Exceptions.Exceptions import TM1pyVersionException, TM1pyNotAdminException, TM1pyNotDataAdminException, \

    TM1pyNotSecurityAdminException, TM1pyNotOpsAdminException, TM1pyVersionDeprecationException




try:

    import pandas as pd

    import numpy as np




    _has_pandas = True

except ImportError:

    _has_pandas = False




# --- parameters and settings

PORTS_TO_EXCLUDE = []

# TM1 connection settings (IntegratedSecurityMode = 1 )

ADDRESS = 'localhost'

USER = 'admin'

PWD = 'apple'




# ===== define a function to be called in the code

def get_all_servers_from_adminhost(adminhost='localhost', port=None, use_ssl=False) -> List:

    from TM1py.Objects import Server

    """ Ask Adminhost for TM1 Servers

    :param adminhost: IP or DNS Alias of the adminhost

    :param port: numeric port to connect to adminhost

    :param ssl: True for secure connection

    :return: List of Servers (instances of the TM1py.Server class)

    """




    if not use_ssl:

        conn = http_client.HTTPConnection(adminhost, port or 5895)

    else:

        conn = http_client.HTTPSConnection(adminhost, port or 5898, context=ssl._create_unverified_context())

    request = '/api/v1/Servers'

    conn.request('GET', request, body='')

    response = conn.getresponse().read().decode('utf-8')

    response_as_dict = json.loads(response)

    servers = []

    print (response_as_dict) # --- as inside function will not show ---

    for server_as_dict in response_as_dict['value']:

        server = Server(server_as_dict)

        servers.append(server)

    return servers




# ===== end of function by go back to beginning of line




# get TM1 models registered with the admin server

tm1_instances_on_server = get_all_servers_from_adminhost(ADDRESS, None, True)

# --- show the list of servers with data as dict

print (tm1_instances_on_server)




# --- for each item in list do this

for tm1_instance in tm1_instances_on_server:




        # get TM1 server information

        port = tm1_instance.http_port_number

        # --- show one value for that server from a dict

        print (tm1_instance.last_updated)

        print (port)




        if port in PORTS_TO_EXCLUDE:

            continue




        ssl = tm1_instance.using_ssl

        # --- connect to the tm1 server to get some more values

        tm1 = TM1Service(address=ADDRESS, port=port, user=USER, password=PWD, namespace='', gateway='', ssl=ssl)

# --- use the function 

        active_configuration = tm1.server.get_active_configuration()

        # print (active_configuration)

        print (active_configuration['Access']['HTTP'])
The last print line use more than one element to find the value to show.

print (tm1_instances_on_server) show the content of that variable, to be a list of dictionary’s.

All print statement in code, will be a line in the terminal window shown above. Use print to debug you code when you develop.

https://www.datacamp.com/tutorial/setting-up-vscode-python 

Solution:

print (active_configuration[‘Access’][‘HTTP’]) , you need to add the elements of the other lists inside the list, to get a value.

Traceback (most recent call last):
File “c:\temp\test2.py”, line 106, in <module>
print (active_configuration[‘Access’][‘Administration’])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
KeyError: ‘Administration’   = you get a error if the key does not exist in the combo object of list and dict.

A Python dictionary (aka dict) is a series of key-value pairs referenced by key name. Dicts are delimited by curly braces. Key-value pairs are separated by commas. A key is separated from its value by a colon.

A list is an ordered collection of items, whereas a dictionary is an unordered data collection in a key: value pair. Elements from the list can be accessed using the index, while the elements of the dictionary can be accessed using keys.

Add this to the code to get a better view of the options:

from pprint import pprint

pprint (vars())

Above you can see the keys you can use to list the values in the print statement from the dict/list.

print (active_configuration[‘Access’][‘CAM’][‘ClientPingCAMPassport’]) will give you the value P0DT00H15M00S.

 

More Information:

https://packetpushers.net/blog/how-to-reference-nested-python-lists-dictionaries/ 

https://readthedocs.org/projects/tm1py/downloads/pdf/latest/ 

https://www.tm1forum.com/viewtopic.php?t=15531 

https://www.shiksha.com/online-courses/articles/difference-between-list-and-dictionary-in-python/ 

https://www.geeksforgeeks.org/difference-between-list-and-dictionary-in-python/

https://youtu.be/daefaLgNkw0?si=-RmMgixEKJtrtm4B

https://www.zyte.com/blog/json-parsing-with-python/ 

https://www.digitalocean.com/community/tutorials/python-pretty-print-json

Example of how to print a dict value:

import json
from types import SimpleNamespace

data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
print(x.name, x.hometown.name, x.hometown.id)

https://www.tutorialspoint.com/how-to-print-all-the-keys-of-a-dictionary-in-python 

https://www.tutorialspoint.com/how-to-print-all-the-values-of-a-dictionary-in-python

https://www.altcademy.com/blog/how-to-print-a-dictionary-in-python/

https://favtutor.com/blogs/print-object-attributes-python

https://www.geeksforgeeks.org/how-to-create-a-list-of-object-in-python-class/

https://flexiple.com/python/python-print-list

https://blog.enterprisedna.co/python-how-to-print-a-list-6-ways-you-need-to-know/

https://code.visualstudio.com/docs/languages/python 

https://code.visualstudio.com/docs/python/python-tutorial