Are there any datatype in python /collections module that would let me reduce my dictionary having same values (not into defaultdict though):
d = {'a': 'X', 'b': 'X', 'c': 'X', 'd': 'X', 'e': 'X', 'f': 'Z'}
to something smaller like
d = {('a','b','c','d','e'): 'X', ('f',): 'Z'}
So I can get same output 'X' when I pick
d['a'] == 'X'
I'm curious because 'X' is a long text in my code and It would be really easy to change all the values if mentioned only at one place.
CodePudding user response:
Try this!
d = {'a': 'X', 'b': 'X', 'c': 'X', 'd': 'X', 'e': 'X', 'f': 'Z'}
dct = {}
out = {}
for k in d.keys():
if dct.get(d[k], None):
dct[d[k]].append(k)
else:
dct[d[k]] = list(k)
for k in dct.keys():
out[tuple(dct[k])] = k
print(out)
CodePudding user response:
If X
is so big that you don't want it duplicated, you might want to store it separately and use another identifier to reference it. For example, you could do something like:
alias = {1: 'X', 2: 'Z'}
d = {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 2}
# Query
alias[d['a']] == 'X'