Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8855795
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T14:13:01+00:00 2026-06-14T14:13:01+00:00

I want to make a 2d dictionary with multiple keys per value. I do

  • 0

I want to make a 2d dictionary with multiple keys per value. I do not want to make a tuple a key. But rather make many keys that will return the same value.

I know how to make a 2d dictionary using defaultdict:

from collections import defaultdict
a_dict = defaultdict(dict)

a_dict['canned_food']['spam'] = 'delicious'

And I can make a tuple a key using

a_dict['food','canned_food']['spam'] = 'delicious'

But this does not allow me to do something like

print a_dict['canned_food']['spam']

Because ‘canned_food’ is not a key the tuple [‘food’,’canned_food’] is the key.

I have learned that I can simply set many to same value independently like:

a_dict['food']['spam'] = 'delicious'
a_dict['canned_food']['spam'] = 'delicious'

But this becomes messy with a large number of keys. In the first dimension of dictionary I need ~25 keys per value. Is there a way to write the dictionary so that any key in the tuple will work?

I have asked this question before but was not clear on what I wanted so I am reposting. Thank you in advance for any help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T14:13:02+00:00Added an answer on June 14, 2026 at 2:13 pm

    Here is a possible solution:

    from collections import Iterable
    
    class AliasDefaultDict():
        def __init__(self, default_factory, initial=[]):
            self.aliases = {}
            self.data = {}
            self.factory = default_factory
            for aliases, value in initial:
                self[aliases] = value
    
        @staticmethod
        def distinguish_keys(key):
            if isinstance(key, Iterable) and not isinstance(key, str):
                return set(key)
            else:
                return {key}
    
        def __getitem__(self, key):
            keys = self.distinguish_keys(key)
            if keys & self.aliases.keys():
                return self.data[self.aliases[keys.pop()]]
            else:
                value = self.factory()
                self[keys] = value
                return value
    
        def __setitem__(self, key, value):
            keys = self.distinguish_keys(key)
            if keys & self.aliases.keys():
                self.data[self.aliases[keys.pop()]] = value
            else:
                new_key = object()
                self.data[new_key] = value
                for key in keys:
                    self.aliases[key] = new_key
                return value
    
        def __repr__(self):
            representation = defaultdict(list)
            for alias, value in self.aliases.items():
                representation[value].append(alias)
            return "AliasDefaultDict({}, {})".format(repr(self.factory), repr([(aliases, self.data[value]) for value, aliases in representation.items()]))
    

    Which can be used like so:

    >>> a_dict = AliasDefaultDict(dict)
    >>> a_dict['food', 'canned_food']['spam'] = 'delicious'
    >>> a_dict['food']
    {'spam': 'delicious'}
    >>> a_dict['canned_food']
    {'spam': 'delicious'}
    >> a_dict
    AliasDefaultDict(<class 'dict'>, [(['food', 'canned_food'], {'spam': 'delicious'})])
    

    Note there are some edge cases with undefined behavior – such as using the same key for multiple aliases. I feel this makes this data type pretty awful for general use, and I’d suggest that you may be better off changing your program not to need this kind of overly convoluted structure instead.

    Also note this solution is for 3.x, under 2.x, you will want to swap out str for basestring, and self.aliases.keys() for self.aliases.viewkeys().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I think I want to make a 2D dictionary with multiple keys per value.
Possible Duplicate: How do I make a dictionary with multiple keys to one value?
I've seen posts here on how to make a dictionary that has multiple values
I have a dictionary of keywords that I want to make available for autocomplete/suggestion
I want to make a C# Dictionary in which the key is the string
I want to make a dictionary that has named LINQ Expressions, since I cannot
I want to make a WindowBaseClass that derives from Window but has a few
I want to make an attribute that will allow me to specify some method
I have a problem. I want to make a dictionary that translates english words
Sorry google translate make mistake, to many mistake, i want make an alarm in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.