You can use a list comprehension.

result = list(result)
new_result = [result[i] for i in list_of_indices]
Answer from luthervespers on Stack Overflow
🌐
Readthedocs
midict.readthedocs.io
MIDict (Multi-Index Dict) — MIDict 0.1 documentation
MIDict is an ordered “dictionary” with multiple indices where any index can serve as “keys” or “values”, capable of assessing multiple values via its powerful indexing syntax, and suitable as a bidirectional/inverse dict (a drop-in replacement for dict/OrderedDict in Python 2 & 3).
🌐
Python Guides
pythonguides.com › python-dictionary-index
Find the Index of Items in a Python Dictionary
May 23, 2024 - These approaches are list comprehension, for loop and enumerate() function. To find the index in the dictionary, you can use the for loop where, in each iteration, an index will printed based on the number of elements in the dictionary.
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.

🌐
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.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.6 documentation
You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend(). It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
🌐
GitHub
github.com › formiaczek › multi_key_dict
GitHub - formiaczek/multi_key_dict: multiple key dictionary for Python (module) · GitHub
Multi-key dict provides also extended interface for iterating over items and keys (e.g. by the key type), which might be useful when creating, e.g. dictionaries with index-name key pair allowing to iterate over items using either: names or indexes.
Starred by 30 users
Forked by 16 users
Languages   Python
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-key-index-in-dictionary
Key Index in Dictionary - Python - GeeksforGeeks
February 11, 2025 - This method builds a dictionary using dictionary comprehension that maps each key to its index, allowing O(1) lookups. It is efficient when multiple lookups are required.
🌐
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
🌐
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…
🌐
GeeksforGeeks
geeksforgeeks.org › python-initialize-dictionary-with-multiple-keys
Python | Initialize dictionary with multiple keys | GeeksforGeeks
May 2, 2023 - 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.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Get the index of the values in python dict - Curriculum Help - The freeCodeCamp Forum
April 30, 2021 - say I have this dict with the values and I want to get the index of each element of the values for either key. I have tried different things but nothing has worked yet. Any help my_dict = { "Up": [1,2,3,4], "Down": [5,6] } I tried this indx_val= [[y for y in x] for x in my_dict.values() if my_dict.keys() == "Up"] Edit I tried this too: my_keys = ' '.join([key for key in my_dict]) indx_val= [[y for y in x] for x in my_dict.values() if my_keys == "Up"] expected output [[0,1,2,3]]...
Top answer
1 of 1
1

In order to be able to create a dictionary from your dataframe, such that the keys are tuples of combinations (according to your example output), my idea would be to use a Pandas MultiIndex. This will then generate a dictionary of the form you want.

First I just recreate your example dataframe (would be nice if you provide this code in the future!):

import pandas as pd

# Create the example dataframe
df = pd.DataFrame(["4-Grain Flakes", "4-Grain Flakes, Gluten Free", "4-Grain Flakes, Riihikosken Vehnämylly"])
df["id"] = [11005, 35146, 32570]
df["energy"] = [1404, 1569, 1443]
df["fibre"] = [11.5, 6.1, 11.2]
df.columns = ["name"] + list(df.columns[1:])

print(df)
                                     name     id  energy  fibre
0                          4-Grain Flakes  11005    1404   11.5
1             4-Grain Flakes, Gluten Free  35146    1569    6.1
2  4-Grain Flakes, Riihikosken Vehnämylly  32570    1443   11.2

Now we can create the combinations of each value in "name" with each of the other column names. I will use lists, within a list comprehension, where I bundle up the values together into tuples. We end with a list of tuples:

names = df.name.tolist()
others = list(df.columns)
others.remove("name")         # We don't want "name" to be included

index_tuples = [(name, other) for name in names for other in others]

We can create the MultiIndex from this list of tuples as follows:

multi_ix = pd.MultiIndex.from_tuples(index_tuples)

Now we can create a new dataframe using out multi_ix. To populate this dataframe, notice that we simple need to row-wise values from columns ["id", "energy", "fibre"]. We can do this easily by extracting as an n * 3 NumPy array (using the values attribute of the dataframe) and then flattening the matrix, using NumPy's ravel method:

df1 = pd.DataFrame(df[others].values.ravel(), index=multi_ix, columns=["data"])

print(df1)

                                                  data
4-Grain Flakes                         id      11005.0
                                       energy   1404.0
                                       fibre      11.5
4-Grain Flakes, Gluten Free            id      35146.0
                                       energy   1569.0
                                       fibre       6.1
4-Grain Flakes, Riihikosken Vehnämylly id      32570.0
                                       energy   1443.0
                                       fibre      11.2

Now we can simply use to to_dict() method of the datframe to create the dictionary you are looking for:

nutritionValues = df1.to_dict()["data"]

print(nutritionValues)

{('4-Grain Flakes', 'energy'): 1404.0,
 ('4-Grain Flakes', 'fibre'): 11.5,
 ('4-Grain Flakes', 'id'): 11005.0,
 ('4-Grain Flakes, Gluten Free', 'energy'): 1569.0,
 ('4-Grain Flakes, Gluten Free', 'fibre'): 6.1,
 ('4-Grain Flakes, Gluten Free', 'id'): 35146.0,
 ('4-Grain Flakes, Riihikosken Vehnämylly', 'energy'): 1443.0,
 ('4-Grain Flakes, Riihikosken Vehnämylly', 'fibre'): 11.2,
 ('4-Grain Flakes, Riihikosken Vehnämylly', 'id'): 32570.0}

It is also possible to get your final example of a multidict, directly from the multi-indexed dataframe. You need to just use multi-index slicing:

fibre_df = final_df.loc[(slice(None), ["fibre"]), :]
print(fibre_df)

                                                 0
4-Grain Flakes                         fibre  11.5
4-Grain Flakes, Gluten Free            fibre   6.1
4-Grain Flakes, Riihikosken Vehnämylly fibre  11.2

You can then generate a dictionary as before:

d = final_df.loc[(slice(None), ["fibre"]), :].to_dict()[0]
print(d)

{('4-Grain Flakes', 'fibre'): 11.5,
 ('4-Grain Flakes, Gluten Free', 'fibre'): 6.1,
 ('4-Grain Flakes, Riihikosken Vehnämylly', 'fibre'): 11.2}

And you can drop the "fibre" value from the tuple-keys with a simple dictionary comprehension:

final_dict = {k[0]: v for k, v in d.items()}
print(final_dict)

{'4-Grain Flakes': 11.5,
 '4-Grain Flakes, Gluten Free': 6.1,
 '4-Grain Flakes, Riihikosken Vehnämylly': 11.2}
🌐
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.
🌐
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 - A normal dictionary performs a simple mapping of a key to a value. 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.
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608