Constructing a new dict:

dict_you_want = {key: old_dict[key] for key in your_keys}

Uses dictionary comprehension.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

Removing everything in-place:

unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Answer from user395760 on Stack Overflow
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-dictionary-multiple-keys
How To Select Multiple Keys From A Dictionary In Python?
March 18, 2025 - Read How to Convert a Dictionary to a List in Python? One of the best methods for selecting multiple keys from a dictionary is by using the Dictionary comprehension approach.
Discussions

Multiple key access for dicts and dict-like objects - Ideas - Discussions on Python.org
This is just an idea, but I think it would be nice to allow dicts and dict-like objects to allow multiple keys to be accessed at once, using a special iterable type operator ] [1, 3] ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
June 6, 2023
Most Python way to check if one or multiple keys match in a dictionary?
What about if {keyname1, keyname2}.issubset(mydict): otherwise you're stuck with multiple ifs if keyname1 in mydict and keyname2 in mydict: or comprehended if all(k in mydict for k in (keyname1, keyname2)): More on reddit.com
๐ŸŒ r/learnpython
11
3
December 10, 2018
python - How to get multiple dictionary values? - Stack Overflow
1 Python pass array into function and use it in json return ยท 0 how to get only specific values from dictionary using key in python More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python dictionary select multiple keys by index - Stack Overflow
I have a dictionary where I'd like to select multiple keys by index that are out of order. Something like this works for keys in order - ... dictionaries don't have indicies. They are maps from keys to values. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-extract-specific-keys-from-dictionary
Python | Extract specific keys from dictionary - GeeksforGeeks
July 11, 2025 - We have a lot of variations and applications of dictionary containers in Python and sometimes, we wish to perform a filter of keys in a dictionary, i.e extracting just the keys which are present in the particular container.
๐ŸŒ
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):
๐ŸŒ
Python.org
discuss.python.org โ€บ ideas
Multiple key access for dicts and dict-like objects - Ideas - Discussions on Python.org
June 6, 2023 - This is just an idea, but I think it would be nice to allow dicts and dict-like objects to allow multiple keys to be accessed at once, using a special iterable type operator and a listing of requested keys defined wโ€ฆ
๐ŸŒ
Mark Needham
markhneedham.com โ€บ blog โ€บ 2020 โ€บ 04 โ€บ 27 โ€บ python-select-keys-from-map-dictionary
Python: Select keys from map/dictionary | Mark Needham
April 27, 2020 - But what if we want to return the values as well? This is where dictionary comprehensions come in handy. We can tweak our code as follows: >>> {key: x[key] for key in ["a", "b"]} {'a': 1, 'b': 2}
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
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
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-to-randomly-choose-multiple-keys-and-its-value-in-a-dictionary
How to Randomly Select Multiple Keys and Their Values from a Python Dictionary: A Step-by-Step Guide โ€” pythontutorials.net
The random module (built into Python, no extra installation needed). The random.sample(population, k) function selects k unique elements from a population (e.g., a list of dictionary keys) without replacement.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ most python way to check if one or multiple keys match in a dictionary?
r/learnpython on Reddit: Most Python way to check if one or multiple keys match in a dictionary?
December 10, 2018 -

Hello Reddit,

For a single key to match it very easy to check of the key is available:

if "keyname" in mydict:
    #do something with if this key matches

To check if multiple keys are in the dict:

if {"keyname1", "keyname2"}.issubset(mydict):
    #do something if both are in the dict

What I want is to check if one or two are in the dict:

if "keyname1" or "keyname2" in dict:
    #this will not work as it will check: 
    #    ("keyname1") or ("keyname2" in dict) and not 
    #    ("keyname1" or "keyname2") in dict
    #do something if one or more of them matches

How do I achieve this?

๐ŸŒ
LearnPython.com
learnpython.com โ€บ blog โ€บ filter-dictionary-in-python
How to Filter a Python Dictionary | LearnPython.com
December 26, 2022 - Learn how to build your own filters with multiple conditions, then use them to filter Python dictionaries by any combination of keys and values.
๐ŸŒ
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 - 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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ returning keys with matching values when the keys have multiple values
r/learnpython on Reddit: Returning keys with matching values when the keys have multiple values
September 19, 2023 -

Context: I am trying to make a python dictionary where each key has 2 values. The user would enter green or small, and it should return the keys that have the values green or small. This for my personal studies. Not sure how to get this to work.
code below:
```
food_dict = {'pea': {'small', 'green'}, 'pumpkin': {'big', 'orange'}, 'watermelon': {'big', 'green'},'cherry': {'small', 'red'}}
print("do you want food that is small, or food that is green")
foodly_desire = input()
if foodly_desire == "small" or foodly_desire == "green":
print(foodly_desire , "is what you desire, and that desire I shall make subtle recommendationsfor.")
for value in food_dict.values():
if value == foodly_desire:
print(food_dict.values(foodly_desire))
else:
print("I can not help you. My programming restricts me from assisting you unless you wantfood that is small or green. ")
```

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()
๐ŸŒ
Quora
quora.com โ€บ Can-a-Python-dictionary-have-more-than-one-value-for-each-key
Can a Python dictionary have more than one value for each key? - Quora
How do you create a dictionary with multiple values per key (Python, Python 3.x, dictionary, development)? How do I access the dictionary if we have the same keys with different values in Python? What is the best key type to use in Python dictionaries? How do you get a specific key from a ...