I guess you mean this:

class Value:
    def __init__(self, v=None):
        self.v = v

v1 = Value(1)
v2 = Value(2)

d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1

d['b'].v == 2 # True
  • Python's strings and numbers are immutable objects,
  • So, if you want d['a'] and d['b'] to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict, list, set).
  • Then, when you modify the object at d['a'], d['b'] changes at same time because they both point to same object.
Answer from fanlix on Stack Overflow
Top answer
1 of 6
46

I guess you mean this:

class Value:
    def __init__(self, v=None):
        self.v = v

v1 = Value(1)
v2 = Value(2)

d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1

d['b'].v == 2 # True
  • Python's strings and numbers are immutable objects,
  • So, if you want d['a'] and d['b'] to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict, list, set).
  • Then, when you modify the object at d['a'], d['b'] changes at same time because they both point to same object.
2 of 6
22

If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.

However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:

alias = {
    'a': 'id1',
    'b': 'id1',
    'c': 'id2',
    'd': 'id2'
}

dictionary = {
    'id1': 1,
    'id2': 2
}

dictionary[alias['a']]

If you need to add to the dictionary you could write a function like this for using both dictionaries:

def add(key, id, value=None)
    if id in dictionary:
        if key in alias:
            # Do nothing
            pass
        else:
            alias[key] = id
    else:
        dictionary[id] = value
        alias[key] = id

add('e', 'id2')
add('f', 'id3', 3)

While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-initialize-dictionary-with-multiple-keys
Python | Initialize dictionary with multiple keys - GeeksforGeeks
July 12, 2025 - Use the zip() function to combine the keys and default values into a list of tuples. Use dictionary comprehension to convert the list of tuples into a dictionary. Print the original Dictionary and the updated dictionary.
Discussions

multiple values for one key in a dictionary

A dictionary key can only hold one value. But that one value could be a list:

dic = {
    "some_value": [1, 2, 3],
}
More on reddit.com
🌐 r/learnpython
12
20
April 20, 2019
Dictionaries of one key with multiple values.
purchase = int(input("Please enter the code of the item: ")) if purchase in stock: You're converting purchase to an int, but all of the keys in stock are strings. So this will never evaluate to True. More on reddit.com
🌐 r/learnpython
8
0
April 28, 2023
python - A dictionary that allows multiple keys for one value - Code Review Stack Exchange
This is a "cartesian" product, ... M's. In Python this is a walk in the park as we can iterate over both and reuse our __setitem__ method: def iterload(self, key_list, value_list): for key in key_list: for value in value_list: self.__setitem__(key, value) ... An "update" method that maintains the relationship to multiple keys. A "delete" method that can both delete a relationship and all entries associated with a ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
April 4, 2015
Python: How to assign multiple values to a key in dictionary without concatenating the value?
You'd make the value a list, and append to that list to add a new number. There can only be one object associated with a key. More on reddit.com
🌐 r/learnpython
16
5
June 16, 2024
🌐
TutorialsPoint
tutorialspoint.com › article › in-the-python-dictionary-can-one-key-hold-more-than-one-value
In the Python dictionary, can one key hold more than one value?
March 27, 2026 - Python dictionaries can store multiple values per key using containers like lists. Use extend() for flat lists, append() for nested structures, and defaultdict() for automatic key handling.
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch01s06.html
Associating Multiple Values with Each Key in a Dictionary - Python Cookbook [Book]
July 19, 2002 - This recipe shows two easy, efficient ways to achieve a mapping of each key to multiple values. The semantics of the two approaches differ slightly but importantly in how they deal with duplication. Each approach relies on the setdefault method of a dictionary to initialize the entry for a key in the dictionary, if needed, and in any case to return said entry.
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-dictionary-with-keys-having-multiple-inputs
Python Dictionary with Keys having Multiple Inputs - GeeksforGeeks
February 3, 2026 - Each key is a tuple representing multiple inputs. The value can be any data (here, "A" and "B"). Access values using the tuple key. Let's consider an example where we use tuples as dictionary keys to store multiple numbers together, with each tuple mapping to a value.
🌐
Medium
medium.com › internet-of-technology › creating-a-python-dictionary-with-multiple-keys-5bdc50d8adc7
Python: Dictionary with Multiple Keys | Internet of Technology
August 13, 2024 - Consider a clinical setting where blood test reference values vary for neonates, pediatric patients, and adults. We may need to retrieve these values by inputting either the patient’s exact age or their age group category. How can we design a Python dictionary to handle this? ... We will create a custom dictionary class, AgeGroupDict, capable of accepting either an integer representing the patient's age or a string specifying their age group. Here's the implementation: class AgeGroupDict(dict): def __getitem__(self, key): if isinstance(key, int): if key <= 1: age_group = 'Neonate' elif key <= 7: age_group = 'Pediatric' elif key > 7: age_group = 'Adult' else: raise KeyError("Age must be positive.") return super().__getitem__(age_group) elif isinstance(key, str): return super().__getitem__(key) else: raise KeyError("Invalid input.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › dictionaries of one key with multiple values.
r/learnpython on Reddit: Dictionaries of one key with multiple values.
April 28, 2023 -

Hi. What I am trying to do is assign multiple values to one dictionary key. and the way I have figured out this is with a list as a key but I am having a little problem. Below is the code I am trying to run.

stock = {'1001' : ['5','3.5'], '1002' : ['8', '1.50']}

purchase = int(input("Please enter the code of the item: "))
if purchase in stock:
    stock[[purchase][0]] =- 1
    
print(stock)

I have already created a dictionary with keys and values as lists. I am then asking for input about an item code. I then want to check the entered code against the dictionary keys and if the key is valid I want to subtract one from the quantity which is the first element in each value list. ex - there are 5 items with the key '1001', I enter the code '1001', the program should know print out the dictionary saying there are 4 items now remaining woth the code '1001'. The problem I am facing is the deduction is not happening. After I enter the item code the dictionary is printed as it is the desired subtraction is not occurring.

Thank you to anyone who helps.

🌐
Delft Stack
delftstack.com › home › howto › python › dictionary with multiple values in python
Dictionary With Multiple Values in Python | Delft Stack
October 10, 2023 - Usually, we have single values for a key in a dictionary. However, we can have the values for keys as a collection like a list. This way, we can have multiple elements in the dictionary for a specific key.
🌐
GeeksforGeeks
geeksforgeeks.org › python › search-for-value-in-the-python-dictionary-with-multiple-values-for-a-key
Search for Value in the Python Dictionary with Multiple Values for a Key - GeeksforGeeks
July 23, 2025 - In conclusion, when working with dictionaries having multiple values for a key, various approaches can be used for efficient value search. Utilizing a list as the value provides simplicity, while defaultdict ensures default values for absent keys. A dictionary of sets offers uniqueness in values, and using the get() method allows for concise searches, as demonstrated in the examples.
🌐
Python Guides
pythonguides.com › python-dictionary-multiple-values
How to Create a Dictionary with Multiple Values Per Key
November 12, 2025 - Learn how to create a Python dictionary with multiple values per key using lists, sets, and defaultdict. Step-by-step examples and best practices for beginners.
Top answer
1 of 1
10

I want to build a dictionary that allows multiple keys for one value:

This is a very basic relational database.

So the first piece of feedback is that new programmers often start coding with poorly defined test-cases or non-normalised test-cases whereby they get lost developing their test portfolio. If you would have started with clarifying your case, I'm sure you would have cracked this problem.

Let's start defining our operations from examples

Sometimes we will have the database maintaining links:

  • from 1 key to 1 value
  • from 1 key to N values
  • from N keys to 1 value
  • from N keys to N values

A dictionary can hold 1 key to N values, but not N keys to 1 value.

Fortunately the reverse operation of N keys to 1 value is the reverse of the dictionary, so we can trick around this by creating a class:

class Database(object):
    """ A dictionary that allows multiple keys for one value """

    def __init__(self):
        self.keys = {}
        self.values = {}

Next we need figure out how to get data into the database. This is similar to the SQL INSERT STATEMENT, where we maintain both our keys and values in single transactions:

def __setitem__(self, key, value):

Lets first insert a new key, whilst keeping in mind that the value might already exist:

    if key not in self.keys:  
        if value not in self.values:  # it's a new value
            self.keys[key] = set()  # a new set
            self.keys[key].add(value)
            self.values[value] = set()  # a new set
            self.values[value].add(key)
        elif value in self.values:
            self.keys[key] = set()  # a new set
            self.keys[key].add(value)
            self.values[value].add(key) # (1)

(1) a new key to a known value only means an update to the values.

Next we worry about if it's a new relationship with a new value:

    elif key in self.keys:  # 
        self.keys[key].add(value)
        if value not in self.values:
            self.values[value] = set()
            self.values[value].add(key)
        elif value in self.values:
            self.values[value].add(key)

We have now implemented the INSERT STATEMENT in our database.

Now it's time to worry about how to delete records and relationships. For this we hack the __delitem__ function to both take a key and a value. Why? Because otherwise we won't know whether the user wants to delete a single relationship only, OR all entries associated with the key

I thereby choose that:

  • if the value is None I delete every relationship associated with the key.
    • if the value is a valid relationship between the key and value, then I only delete that specific relationship.

This is how it works:

def __delitem__(self, key, value=None): 
    if value is None:
        # All the keys relations are to be deleted.
        try:
            value_set = self.keys[key]
            for value in value_set:
                self.values[value].remove(key)
                if not self.values[value]:
                    del self.values[value]
            del self.keys[key]  # then we delete the key.
        except KeyError:
            raise KeyError("key not found")
    else:  # then only a single relationships is being removed.
        try:
            if value in self.keys[key]:  # this is a set.
                self.keys[key].remove(value)
                self.values[value].remove(key)
            if not self.keys[key]:  # if the set is empty, we remove the key
                del self.keys[key]
            if not self.values[value]:  # if the set is empty, we remove the value
                del self.values[value]
        except KeyError:
            raise KeyError("key not found")

Now we can add and delete. But how about bulk updates? They constitute a special case because __setitem__ can't see that you want to propagate your update onto multiple values. So we need to tell it WHAT to update. Here is a proposal that uses the relationship between the key, the old value and the new value that should be accessible to all keys that other would have a relationship with the old value:

def update(self, key, old_value, new_value):
    if old_value in self.keys[key]:
        affected_keys = self.values[old_value]
        for key in affected_keys:
            self.__setitem__(key, new_value)
            self.keys[key].remove(old_value)
        del self.values[old_value]
    else:
        raise KeyError("key: {} does not have value: {}".format(key,old_value))

So far so good. A slightly annoying thing is that we can't really read what is in the database even though we can get things in and delete them. This calls for the SELECT STATEMENT - or python's __getitem__ method. But(!) we need to be careful, as our database stores data internally as a sets that are accessible from keys. So we need to unpack them onto something useful. As I like working with lists, I have chosen to provide lists, unless its a single value, whereby I only return the value itself:

def __getitem__(self, item):
    values = self.keys[item]
    if len(values) > 1:
        return sorted(list(values))
    elif len(values) == 1:
        return list(values)[0]

Now we just miss one thing to pass all your test: The bulk loading method where you map N keys to M values. This is a "cartesian" product, which is a fancy word all N's maps to all M's. In Python this is a walk in the park as we can iterate over both and reuse our __setitem__ method:

def iterload(self, key_list, value_list):
    for key in key_list:
        for value in value_list:
            self.__setitem__(key, value)

At this point we have implemented:

  • A class for our database
  • A "select" method that is compatible with python d[key]
  • An "insert" method that is compatible with python d[key] = value
  • An "update" method that maintains the relationship to multiple keys.
  • A "delete" method that can both delete a relationship and all entries associated with a key.

Testing

Now I need to test this.

First we load a single key:value pair, where the key is a hashable structure. I chose a tuple with 3 integers:

def test01()
    # hashable key - a tuple
    d = Database()
    k, v = (1, 2, 3), 'magic'
    d[k] = v
    print(d)
    print(d[k])

That works fine as we can see our database object and the value

    # print(d)
    <__main__.Database object at 0x7fd9c3d17048>

    # print(d[k])
    magic

Next we can test our bulk-load method: iterload together with the "many keys - shared value" which is focal in your problem:

def test02():
    # non-hashable key - a list - becomes a many-key shared value
    d = Database()
    keys, value = [1, 2, 3], ['magic']
    d.iterload(keys, value)
    assert d[1] == d[2] == d[3]

This also works as our assertion in the last line doesn't complain: The value of d[1]...d[3] are the same: The text string magic

I add two more tests, which should look very familiar to you, though with minor exceptions:

def test03():
    d = Database()
    k, v = ['what', 'ever'], ['test']
    d.iterload(k,v)
    assert d['what'] == d['ever']
    d['what'] = 'testing'
    try:
        assert d['what'] == d['ever']
    except AssertionError:
        assert True

In test03 I need to pack the value into a list, because iterload needs two iterables. I could made my code much harder to read by accounting for many different cases, but I think the programmer should build a function for one thing and make it clear for future recall of what the function is supposed to do.

In test04 - below - I have added the usage of the update function.

def test04():
    d = Database()
    v = 'test'
    keys, values = ['what', 'ever'], [v]
    d.iterload(keys, values)
    d['whatever'] = 'test'
    assert v == d['whatever']
    assert v == d['what']
    assert d['whatever'] == d['what']
    d.update('whatever', 'test', 'new test')
    a, b = d['whatever'], d['what']
    assert a == b

Everything Together

Here you go:

__author__ = 'root-11'


class Database(object):
    """ A dictionary that allows multiple keys for one value """

    def __init__(self):
        self.keys = {}
        self.values = {}

    def __getitem__(self, item):  # <---SQL SELECT statement
        values = self.keys[item]
        if len(values) > 1:
            return sorted(list(values))
        elif len(values) == 1:
            return list(values)[0]

    def __setitem__(self, key, value):
        if key not in self.keys:  # it's a new key <---SQL INSERT statement
            if value not in self.values:  # it's a new value
                self.keys[key] = set()  # a new set
                self.keys[key].add(value)
                self.values[value] = set()  # a new set
                self.values[value].add(key)
            elif value in self.values:
                self.keys[key] = set()  # a new set
                self.keys[key].add(value) # a new key
                self.values[value].add(key)  # but just an update to the values
        elif key in self.keys:  # it's a new relationships
            self.keys[key].add(value)
            if value not in self.values:
                self.values[value] = set()
                self.values[value].add(key)
            elif value in self.values:
                self.values[value].add(key)

    def update(self, key, old_value, new_value):
        """update is a special case because __setitem__ can't see that
        you want to propagate your update onto multiple values. """
        if old_value in self.keys[key]:
            affected_keys = self.values[old_value]
            for key in affected_keys:
                self.__setitem__(key, new_value)
                self.keys[key].remove(old_value)
            del self.values[old_value]
        else:
            raise KeyError("key: {} does not have value: {}".format(key,old_value))

    def __delitem__(self, key, value=None):  # <---SQL DELETE statement
        if value is None:
            # All the keys relations are to be deleted.
            try:
                value_set = self.keys[key]
                for value in value_set:
                    self.values[value].remove(key)
                    if not self.values[value]:
                        del self.values[value]
                del self.keys[key]  # then we delete the key.
            except KeyError:
                raise KeyError("key not found")
        else:  # then only a single relationships is being removed.
            try:
                if value in self.keys[key]:  # this is a set.
                    self.keys[key].remove(value)
                    self.values[value].remove(key)
                if not self.keys[key]:  # if the set is empty, we remove the key
                    del self.keys[key]
                if not self.values[value]:  # if the set is empty, we remove the value
                    del self.values[value]
            except KeyError:
                raise KeyError("key not found")

    def iterload(self, key_list, value_list):
        for key in key_list:
            for value in value_list:
                self.__setitem__(key, value)

def test01():
    # hashable key - a tuple
    d = Database()
    k, v = (1, 2, 3), 'magic'
    d[k] = v
    print(d)
    print(d[k])


def test02():
    # non-hashable key - a list - becomes a many-key shared value
    d = Database()
    keys, value = [1, 2, 3], ['magic']
    d.iterload(keys, value)
    assert d[1] == d[2] == d[3]


def test03():
    d = Database()
    k, v = ['what', 'ever'], ['test']
    d.iterload(k,v)
    assert d['what'] == d['ever']
    d['what'] = 'testing'
    try:
        assert d['what'] == d['ever']
    except AssertionError:
        assert True


def test04():
    d = Database()
    v = 'test'
    keys, values = ['what', 'ever'], [v]
    d.iterload(keys, values)
    d['whatever'] = 'test'
    assert v == d['whatever']
    assert v == d['what']
    assert d['whatever'] == d['what']
    d.update('whatever', 'test', 'new test')
    a, b = d['whatever'], d['what']
    assert a == b


def do_all():
    for k, v in sorted(globals().items()):
        if k.startswith("test") and callable(v):
            v()

if __name__ == "__main__":
    do_all()
🌐
Medium
medium.com › @maneesh1.kumar › storing-multiple-values-in-python-dictionary-9b310b5931f2
Storing Multiple values in Python Dictionary | by Maneesh Kumar | Medium
September 21, 2023 - With this structure, it’s easy to store any number of attributes for each key in the index. These attributes are also straightforward to manage and visualize. Moreover, when dealing with another Pandas DataFrame, such as positions or P&L by ticker, it’s extremely convenient to perform operations like joining using built-in Pandas commands like pd.concat and .join. In summary, we’ve explored various ways to store multiple values in Python.
🌐
Reddit
reddit.com › r/learnpython › python: how to assign multiple values to a key in dictionary without concatenating the value?
r/learnpython on Reddit: Python: How to assign multiple values to a key in dictionary without concatenating the value?
June 16, 2024 -

I'm still a beginner (but having fun!!) Here is my code with the output:

p_book = {}

while True:

phone_book = int(input("command (1 search, 2 add, 3 quit):"))

if phone_book == 3:

print("quitting...")

break

elif phone_book == 1:

name = input("name: ")

if name in p_book:

print(p_book[name])

else:

print("no number")

elif phone_book == 2:

name = input("name: ")

num = input("number: ")

if name in p_book:

if num not in p_book:

p_book[name] += num

print("ok!")

else:

continue

elif name not in p_book:

p_book[name] = num

print("ok!")

________________________________________________________________________________________________________

my input was name: Mary and 2 different "Phone numbers": 045-1212344 and 045-9999999

here is the output:

command (1 search, 2 add, 3 quit):2

name: Mary

number: 045-1212344

ok!

command (1 search, 2 add, 3 quit):2

name: Mary

number: 045-9999999

ok!

command (1 search, 2 add, 3 quit):1

name: Mary

045-1212344045-9999999

_____________________________________________________________________________________________________

what I need to output is the two numbers as separate numbers. I know if I have the two numbers (values) in the dictionary listed separately I can use a for list to print out the numbers on a separate line like so:

name: Mary

045-1212344

045-9999999

_______________________________________________________________________________________________________

Happy Father's Day!!!

🌐
Medium
medium.com › analytics-vidhya › mapping-keys-to-multiple-values-in-a-dictionary-b5022de9dd0e
Two common ways used in Python to add multiple values to a Dictionary key
June 20, 2020 - Multidict is a dictionary where several values are mapped to one key. ... Here, key ‘d’ has 2 elements and key ‘e’ has 3 elements.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-get-multiple-values-from-dictionary
Get multiple values from a Dictionary in Python | bobbyhadz
April 9, 2024 - We used a list comprehension to iterate over the collection of dictionary keys. List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition. On each iteration, we access the current key and return the corresponding value. The new list only contains the values of the specified keys. ... Copied!my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, 'topic': 'Python' } keys = ['name', 'site'] values = [my_dict[key] for key in keys] print(values) # 👉️ ['Borislav Hadzhiev', 'bobbyhadz.com']
🌐
PyPI
pypi.org › project › multi_key_dict
multi_key_dict
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Top answer
1 of 7
38

What type are the values?

dict = {'k1':MyClass(1), 'k2':MyClass(1)}

will give duplicate value objects, but

v1 = MyClass(1)
dict = {'k1':v1, 'k2':v1}

results in both keys referring to the same actual object.

In the original question, your values are strings: even though you're declaring the same string twice, I think they'll be interned to the same object in that case


NB. if you're not sure whether you've ended up with duplicates, you can find out like so:

if dict['k1'] is dict['k2']:
    print("good: k1 and k2 refer to the same instance")
else:
    print("bad: k1 and k2 refer to different instances")

(is check thanks to J.F.Sebastian, replacing id())

2 of 7
13

Check out this - it's an implementation of exactly what you're asking: multi_key_dict(ionary)

https://pypi.python.org/pypi/multi_key_dict (sources at https://github.com/formiaczek/python_data_structures/tree/master/multi_key_dict)

(on Unix platforms it possibly comes as a package and you can try to install it with something like:

sudo apt-get install python-multi-key-dict

for Debian, or an equivalent for your distribution)

You can use different types for keys but also keys of the same type. Also you can iterate over items using key types of your choice, e.g.:

m = multi_key_dict()
m['aa', 12] = 12
m['bb', 1] = 'cc and 1'
m['cc', 13] = 'something else'

print m['aa']   # will print '12'
print m[12]     # will also print '12'

# but also:
for key, value in m.iteritems(int):
    print key, ':', value
# will print:1
# 1 : cc and 1
# 12 : 12
# 13 : something else

# and iterating by string keys:
for key, value in m.iteritems(str):
    print key, ':', value
# will print:
# aa : 12
# cc : something else
# bb : cc and 1

m[12] = 20 # now update the value
print m[12]   # will print '20' (updated value)
print m['aa']   # will also print '20' (it maps to the same element)

There is no limit to number of keys, so code like:

m['a', 3, 5, 'bb', 33] = 'something' 

is valid, and either of keys can be used to refer to so-created value (either to read / write or delete it).

Edit: From version 2.0 it should also work with python3.

🌐
Note.nkmk.me
note.nkmk.me › home › python
Set Operations on Multiple Dictionary Keys in Python | note.nkmk.me
January 28, 2024 - Built-in Types - Dictionary view objects — Python 3.12.1 documentation · To extract keys common to multiple dictionaries, use the keys() method and the & operator. d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'b': 2, 'c': 4, 'd': 5} intersection_keys ...
🌐
Omics
python.omics.wiki › data-structures › dictionary › multiple-keys
Python by Examples - Multiple keys
Multi-key combinations to access values a) Table/matrix representation using tupels Tupels are 'hashable' objects and hence can be used as a key in python dictionaries. {(key_part_1, key_part_2):