简体   繁体   English

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

[英]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.

相关问题 如何按多个元素对字典列表进行排序 - How do I sort a list of dictionaries by more than one element 字典,使用.get添加多个值 - Dictionaries, adding more than one value with .get 如何遍历包含多个键的字典列表,并更改不同的键值? - How to loop through a list of dictionaries that contain more than one key, and change different key values? Python-比较两个字典,创建一个仅在一个字典中出现的唯一项的新字典 - Python - Compare two dictionaries, create a new dictionary of unique items which occur only in one dictionary 根据一个词典列表中的键创建一个新的词典列表 - create a new list of dictionaries based on a key in one list of dictionaries 如何通过2个键对词典列表进行排序,其中一个键基于任意列表 - How to sort a list of dictionaries by 2 keys, one of which is based on an arbitrary list 将字典列表合并为一个的更多 Pythonic 方式? - More Pythonic Way to Merge a list of dictionaries into one? Python:如何过滤字典列表以获取一个键的所有值 - Python: How to filter a list of dictionaries to get all the values of one key 如何将具有相同键的词典值合并到词典列表中? - How to merge values of dictionaries with same key into one from a list of dictionaries? 将字典合并到一个具有唯一 ID 的字典列表中 - Merging dictionaries into one list of dictionaries on a unique id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM