键值对/矩阵矩阵

时间:2016-08-02 08:24:26

标签: python

我有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

4 个答案:

答案 0 :(得分:1)

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

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 :(得分:0)

作为一般方法(我假设你有一个dicts列表,在这里,你可以按照“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)

答案 2 :(得分: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]}

答案 3 :(得分: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]
相关问题