在 Python 中,如果两个值相同,则从嵌套字典中删除重复条目
考虑这种字典格式。
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
我想删除所有具有相同名称和作者的项目。
我可以通过将所有键放入一个集合中来轻松删除基于键的重复条目,并且可能将其扩展以处理特定值,但这似乎是一个昂贵的操作,需要多次迭代字典。我不知道如何以有效的方式使用两个值来做到这一点。这是一本包含数千条条目的词典。
Consider this dictionary format.
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
I want to remove all items which have the same name and author.
I can easily remove duplicate entries based on keys by putting all keys in a set, and maybe expand this to work on a specific value, but this seems like a costly operation which iterates over a dictionary multiple times. I wouldn't know how to do this with two values in an efficient way. It's a dictionary with thousands of items.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遍历字典,跟踪遇到的
(name,author)
元组,并删除已经遇到的元组:Iterate through the dictionary, keeping track of encountered
(name, author)
tuples as you go and remove those that you have already encountered:让我们看看这是否有效...
Let's see if this works...