2017-07-05 295 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]] –