繁体   English   中英

如何在词典列表中用一个新词典替换出现一次以上的所有词典?

[英]How to replace in list of dictionaries all dictionaries which occur more than one time with just one new?

如何在字典列表中替换(每个字典具有相同或不同值的相同键)所有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 我可以通过迭代计数存在性并将所有具有多个存在和替换的组合放入列表中,但是有没有更快的方法?

[{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'}]

由于在列表中搜索速度很慢,因此值得一本字典词典作为中介,特别是如果以后要按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']}

从长远来看,您可能想测试一下这实际上是否更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM