我有幾個對象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
我有幾個對象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
如果使用熊貓,你可以這樣做:
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.
作爲一般的做法(我假設你已經類型的字典,這裏的列表,你是細與具有「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)
這裏是另一個簡單的解決方案,它不使用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]}
這裏是一種非常粗糙的和可能低效溶液
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]
你能發佈一個最小的輸入,期望的輸出和你到目前爲止試圖達到的目標嗎? –
@ColonelBeauvel,我更新了我的問題 – Roby
你已經試過了嗎? – DeepSpace