2013-08-29 49 views
0

如何在词典列表中替换(每个词典具有相同或不同值的相同键)所有词典with same values of keys id and type which occur more than 0ne time with just one new dictionary with type group? 我可以通过迭代计数存在,并列出与多个存在和替换的所有组合,但有更快的方式吗?如何在词典列表中替换出现一次以上的所有词典,只有一个新词?

[{id:1, type:1, content:'txt'},{id:2, type:1, content:'abc'},{id:1, type:1, content:'yup'},{id:1, type:1, content:'dmg'}] 

将成为

[{id:1, type:'group', content:'txt'},{id:2, type:1, content:'abc'}] 
+0

你对'content'做了什么? –

+0

那么,显示你得到的是不是工作,或者你觉得是非常糟糕的设计。也许你已经有了最高效的代码,但是没有人看不到它。 – Evert

回答

0

因为在列表中进行搜索是缓慢的,它可能是值得生产的字典词典作为中间,特别是如果你将ID在以后搜索。如有必要,您可以稍后转换回列表。

#ld = the list of dictionaries to be processed 
nd = {} 
for dict in ld: 
    i= dict['id'] 
    if i in nd: 
     if nd[i]['type'] != 'group': 
      nd[i]={'type':'group', 'content':'txt'} 
    else: 
     nd[i]={'type':dict['type'],'content':dict['content']} 

你会想要测试,看看这是否实际上是更快的长期运行。

相关问题