我有這種形式的詞典列表:變換辭典蟒蛇
d_old=[{"color":"red","store":"1","s_d":{"M":"1","L":"2"}},
{"color":"blue","store":"2","s_d":{"S":"3","XL":"4"}}]
我的目標是變成這樣:
d_new=[{"color":"red","store":"1","Size":"M", "Stock":"1"},
{"color":"red","store":"1","Size":"L", "Stock":"2"},
{"color":"blue","store":"2","Size":"S", "Stock":"3"},
{"color":"blue","store":"2","Size":"XL", "Stock":"4"}]
我寫了這一點,它的工作原理,但我想知道,如果有一個更好的方法: 鍵總是定義在一個列表中,這裏爲了簡化,只顯示了兩個鍵,還有更多。
def transform_data(d_old):
d_new_list =[]
headers=["color","store"]
for d in d_old:
for key,value in d["s_d"].items():
temp_dict = {header:d[header] for header in headers}
temp_dict["Size"] = key
temp_dict["Stock"] = value
d_new_list.append(temp_dict)
如果你不想硬編碼的鑰匙,試試我的解決方案。 – McGrady