How to check for redundant combinations in a python dictionary -
i have following python dictionary tuples keys , values:
{(a, 1): (b, 2), (c, 3): (d, 4), (b, 2): (a, 1), (d, 4): (c, 3), }
how unique set of combinations between keys , values? such (a,1):(b,2)
appears, not (b,2):(a,1)
?
d = {('a', 1): ('b', 2), ('c', 3): ('d', 4), ('b', 2): ('a', 1), ('d', 4): ('c', 3), } >>> dict(set(frozenset(item) item in d.items())) {('a', 1): ('b', 2), ('d', 4): ('c', 3)}
this works converting each key/value pair in dictionary set. important because pair (a, b)
, set([a, b])
equal set([b, a])
. perfect if take of key/value sets , add them set, eliminate of duplicates. can't set
type because isn't hashable, use frozenset
instead. built-in dict()
function can accept iterable of key/value pairs argument, can pass in our set of key/value pairs , work expected.
a great point made in comments causing issue if maps itself, example if had d[('a', 1)] = ('a', 1)
, work around can use sorted()
suggested in comment:
d = {('a', 1): ('a', 1), ('c', 3): ('d', 4), ('d', 4): ('c', 3), } >>> dict(sorted(item) item in d.items()) {('a', 1): ('a', 1), ('c', 3): ('d', 4)}
this has benefit duplicates sorted order consistently give "smaller" of elements key , "larger" value.
however on python 3.x need careful if keys , values may have different types, since sorted()
raise exception unless of elements in iterable same type:
>>> d = {1: 'a', 'a': 1} >>> dict(sorted(item) item in d.items()) traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 1, in <genexpr> typeerror: unorderable types: int() < str()
Comments
Post a Comment