Python - Subtract a list of dicts from another

Python - Subtract a list of dicts from another,第1张

Python - Subtract a list of dicts from another

There are probably many pitfalls to a generic approach like this, but if your
dictionaries are of mostly primitives, and not huge, you can do something like
this:

Assuming your data looks something like this:

networks = [        {'address': '192.168.1.1'},        {'address': '127.0.0.1'},    ]missing = [        {'address': '127.0.0.1'}    ]

You can turn the lists of dictionaries into lists tuples (which are hashable)

def make_hashable(d):    return (frozenset(x.iteritems()) for x in d)networks_hashable = make_hashable(networks)missing_hashable = make_hashable(missing)

Then subtract

diff = set(networks_hashable).difference(missing_hashable)

Now you have a list of tuples

print list(diff)

or, convert back to dictionaries

print [dict(x) for x in diff]

Update

I’ve changed the definition of

make_hashable
based on @gnibbler’s comment.



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5617693.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存