Manipulating dictionaries in python
From raju
populate a dictionary by calling a function on each element of a list
>>> def sqr(x): ... return x*x ... >>> a = [1.1, 2.2, 3.3] >>> b = {k:sqr(k) for k in a} >>> a [1.1, 2.2, 3.3] >>> b {1.1: 1.2100000000000002, 2.2: 4.840000000000001, 3.3: 10.889999999999999}
Ref:- https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python
merge python dictionaries
create a dictionary from a list with same value
>>> a = ['a', 's', 'd', 'as', 'sd', 'asd']; >>> v = 42 >>> d = {k:v for k in a} >>> d {'asd': 42, 'sd': 42, 's': 42, 'a': 42, 'as': 42, 'd': 42}
Ref:- http://stackoverflow.com/questions/11977730/creating-a-dictionary-with-same-values
load json from a file
import json with open('file.json') as fh: a = json.load(fh)
print a dictionary
Say we have a dictionary d where each element is a map from string to a dataframe. To print the shape of each dataframe, do
>>> for (k,v) in d.items(): ... print("{}, {}".format(k, v.shape)) ... object, (4208, 8) int, (4208, 369) measures, (4208, 369) response, (4208, 1) float, (4208, 1) predictors, (8416, 377) dimensions, (4208, 8)