# Dictionaries

Gregor von Laszewski (laszewski@gmail.com)

## Dotdict

For simple dictionaries we sometimes like to simplify the notation with a . instead of using the []:

You can achieve this with dotdict

from cloudmesh.common.dotdict import dotdict

data = {
"name": "Gregor"
}

data = dotdict(data)


Now you can either call

data["name"]


or

data.name


This is especially useful in if conditions as it may be easier to read and write

if data.name is "Gregor":



and is the same as

if data["name"] is "Gregor":



For more features, see API: dotdict

## FlatDict

In some cases, it is useful to be able to flatten out dictionaries that contain dicts within dicts. For this, we can use FlatDict.

from cloudmesh.common.Flatdict import FlatDict

data = {
"name": "Gregor",
"city": "Bloomington",
"state": "IN"

}
}

flat = FlatDict(data, sep=".")


This will be converted to a dict with the following structure.

flat = {
"name": "Gregor"
}


With sep you can change the sepaerator between the nested dict attributes. For more features, see API: dotdict

## Printing Dicts

In case we want to print dicts and lists of dicts in various formats, we have included a simple Printer that can print a dict in yaml, json, table, and csv format.

The function can even guess from the passed parameters what the input format is and uses the appropriate internal function.

A common example is

from pprint import pprint
from cloudmesh.common.Printer import Printer

data = [
{
"name": "Gregor",
"street": "Funny Lane 11",
"city": "Cloudville"
}
},
{
"name": "Albert",
"street": "Memory Lane 1901",
"city": "Cloudnine"
}
}
]

pprint(data)

table = Printer.flatwrite(data,
sort_keys=["name"],