Roby Roby - 2 years ago 107
Python Question

Matrix of Key-Value Pairs / Dict

I have several objects from

type dict
with different keys. I want to create a table
with all keys
and foreach object one row. If one key isn't available, it should be empty.

For Example:

x1=dict( {"a":2, "b":3})
x2=dict( {"a":2, "b":3, "c":2})

and i want to get something like this:


Answer Source

If you use pandas, you can do this:

import pandas as pd
df = pd.DataFrame({k: [v] for k, v in x1.iteritems()})
df2 = pd.DataFrame({k: [v] for k, v in x2.iteritems()})

df = pd.concat((df, df2), ignore_index=True)

#    a  b   c
# 0  2  3 NaN
# 1  2  3   2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download