2016-08-02 29 views
0

我有几个对象type dict与不同的键。我想创建一个表with all keys和foreach对象一行。如果一个键不可用,它应该是空的。键值对的矩阵/字典

例如:

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

,我想是这样的:

"a","b","c" 
2,3, 
2,3,2 
+1

你能发布一个最小的输入,期望的输出和你到目前为止试图达到的目标吗? –

+0

@ColonelBeauvel,我更新了我的问题 – Roby

+0

你已经试过了吗? – DeepSpace

回答

1

如果使用熊猫,你可以这样做:

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 

注:iteritems()仅适用于Python 2.x.

+1

您可以简单地使用'DataFrame.from_dict'而不是迭代字典。 – DeepSpace

+1

@DeepSpace我认为这不起作用,因为值是标量而不是列表。 –

+0

这工作对我来说,找到http://stackoverflow.com/a/10458567/722695后 – Roby

0

作为一般的做法(我假设你已经类型的字典,这里的列表,你是细与具有“asciibetical”列顺序):

def EmitDictsAsCSV(list_of_dicts): 
    # First, accumulate the full set of dict keys 
    key_set = set() 
    for d in list_of_dicts: 
    key_set.update(d.iterkeys()) 

    # make a sorted list out of them 
    column_names = sorted(key_set) 
    # print the header 
    print ",".join(['"%s"' % c for c in column_names]) 

    # For each dict, loop over the columns and build a row, 
    # use the string representation of the value, if there's 
    # one, otherwise use an empty string, 
    # finish off by printing the row data, separated by commas 
    for d in list_of_dicts: 
    row_data = [] 
    for c in column_names: 
     if c in d: 
     row_data.append(str(d[c])) 
     else: 
     row_data.append("") 
    print ",".join(row_data) 
0

这里是另一个简单的解决方案,它不使用pandas

all_dics = [x1, x2] 
keys = set(key for d in all_dics for key in d) # {'a', 'b', 'c'} 
dic = {key: [None]*len(all_dics) for key in keys} # {'a': [None, None], 'b': [None, None], 'c': [None, None]} 
for j, d in enumerate(all_dics): 
    for key, val in d.iteritems(): 
     dic[key][j] = val 

print dic 
# {'a': [2, 2], 'b': [3, 3], 'c': [None, 2]} 
0

这里是一种非常粗糙的和可能低效溶液

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

z = dict(x1.items() + x2.items()) 
print(z.keys()) 

x1_vals = [] 
x2_vals = [] 
for keys in z.keys(): 
    if keys in x1.keys(): 
     x1_vals.append(x1[keys]) 
    else: 
     x1_vals.append(None) 

    if keys in x2.keys(): 
     x2_vals.append(x2[keys]) 
    else: 
     x2_vals.append(None) 

print (x1_vals) 
print (x2_vals) 

输出

['a', 'c', 'b', 'e', 'd'] 
[2, None, 3, 5, 4] 
[2, 2, 3, None, None]