0

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.

PaxPrz
  • 1,778
  • 1
  • 13
  • 29
  • 3
    While not directly answering your question, a solution i can see is to store each long value in a seperate dictionary or list with numerical indexes, and use the indexes to refer to those values. Especially if the worry is about the easy of changing repeat values or storage it should resolve your issue. You can also create a custom module that does it all for you automatically, but that'd be a bit more complicated. – Zaid Al Shattle Nov 15 '21 at 11:20
  • 1
    Check out [this answers to a similar question](https://stackoverflow.com/questions/1921027/many-to-one-mapping-creating-equivalence-classes) – Mr.Mike Nov 15 '21 at 11:22

2 Answers2

1

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)
Hashir Irfan
  • 315
  • 1
  • 9
0

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'
David
  • 11
  • 2