2017-07-05 161 views
-3

我有一本字典如下:拆分字典分成多個字典

P_ID V1 V2  V3 
100 slow slow high 
100 slow high high 
104 medium high high 
107 slow high high 
107 slow high high 
107 slow high high 
    ... 
    ... 

所以我想分裂這個字典到基於P_ID的值的多個詞典。事情是這樣的:

迪科1:

P_ID V1 V2  V3 
100 slow slow high 
100 slow high high 

迪科2:

P_ID V1 V2  V3 
104 medium high high 

迪科3:

P_ID V1 V2  V3 
107 slow high high 
107 slow high high 
107 slow high high 
+0

創建3個新的字典,遍歷您的舊字典,用一系列的如果,如果其他人,然後做了值添加到正確的字典。 – JoshKopen

+2

「我有一本字典如下:」這是你在那裏的一張不錯的桌子。你的字典是怎麼看的? –

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [在主題](http://stackoverflow.com/help/on-topic)和[如何提問](http://stackoverflow.com/help/how-to-ask)適用於此處。 StackOverflow不是一個設計,編碼,研究或教程服務。向我們展示代碼,而不是文本表格,並指定問題。 – Prune

回答

0

試試這個。可能還有其他的方法,但我認爲這個更簡單。

d = [{'V1': 'slow', 'V2': 'slow', 'V3': 'high', 'P_ID': 100}, 
    {'V1': 'slow', 'V2': 'high', 'V3': 'high', 'P_ID': 100}, 
    {'V1': 'medium', 'V2': 'high', 'V3': 'high', 'P_ID': 104}, 
    {'V1': 'slow', 'V2': 'high', 'V3': 'high', 'P_ID': 107}, 
    {'V1': 'slow', 'V2': 'high', 'V3': 'high', 'P_ID': 107}, 
    {'V1': 'slow', 'V2': 'high', 'V3': 'high', 'P_ID': 107}] 

keys = set([e['P_ID'] for e in d]) 

for k in keys: 
    print [x for x in d if x['P_ID'] == k] 
    print("") 

在線演示:https://repl.it/JOn7

+0

它看起來可以在Python 2.7中使用,但在Python 3.6中卻不行! –

+0

可能是因爲第一個打印語句「缺少」括號......將它們放入代碼中並重試。 –

+0

是的,我注意到了,但是問題出自這個函數:set([e ['P_ID'] for e in]] –