[英]How to replace in list of dictionaries all dictionaries which occur more than one time with just one new?
How to replace in list of dictionaries (every dictionary has same keys with same or different values) all dictionaries with same values of keys id and type which occur more than 0ne time with just one new dictionary with type group
? 如何在字典列表中替换(每个字典具有相同或不同值的相同键)所有
with same values of keys id and type which occur more than 0ne time with just one new dictionary with type group
字典with same values of keys id and type which occur more than 0ne time with just one new dictionary with type group
? I can to this by iteration counting existance and put in list all combination with more than one existance and replace, but is there faster way ? 我可以通过迭代计数存在性并将所有具有多个存在和替换的组合放入列表中,但是有没有更快的方法?
[{id:1, type:1, content:'txt'},{id:2, type:1, content:'abc'},{id:1, type:1, content:'yup'},{id:1, type:1, content:'dmg'}]
will become 会变成
[{id:1, type:'group', content:'txt'},{id:2, type:1, content:'abc'}]
Since searching in lists is slow, it may be worth producing a dictionary of dictionaries as an intermediate, especially if you will be searching by id later. 由于在列表中搜索速度很慢,因此值得一本字典词典作为中介,特别是如果以后要按ID搜索的话。 You can convert back to to the list later if necessary.
如有必要,您可以稍后再转换回列表。
#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']}
You would want to test to see if this is actually any faster in the long run. 从长远来看,您可能想测试一下这实际上是否更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.