Manipulating dictionaries in python

From raju

merge python dictionaries

To merge two python dictionaries

def merge_two_dicts(x, y):
    '''
    Given two dicts, merge them into a new dict as a shallow copy.
    For common keys, the values in y take precedence over values in x.
    '''
    z = x.copy()
    z.update(y)
    return z

Sample usage:

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}
>>> z = merge_two_dicts(x, y)
>>> z
{'a': 1, 'c': 4, 'b': 3}


To merge an undefined number of dicts

def merge_dicts(*dict_args):
    '''
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    '''
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

Given dicts a to g

z = merge_dicts(a, b, c, d, e, f, g) 

will give a new dict z with all the key-value pairs. If same key exists in multiple dictionaries, the right most one will take precedence.

Ref:- http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression

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

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

dictionary to string and string to dictionary conversions

>>> import json
>>> d = {'a':1, 'b':2}
>>> s = json.dumps(d)
>>> d
{'a': 1, 'b': 2}
>>> s
'{"a": 1, "b": 2}'
>>> d2 = json.loads(s)
>>> d2
{'a': 1, 'b': 2}

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)