SoFunction
Updated on 2025-04-11

New methods for dict support multiple keys in Python

In Python, dictionary (dict) is a very powerful data structure that allows us to pass through keys (key) to store and retrieve values ​​(value). Sometimes, we may want to retrieve or manipulate data in the dictionary based on multiple keys. Although Python's dictionary does not directly support indexing with multiple keys, we can implement this with some tricks.

Below, I will show several ways to deal with dictionaries containing multiple keys and provide detailed code examples.

1. Method 1: Use tuples as keys

We can combine multiple keys into a tuple and use this tuple as the key for the dictionary.

(1) Code Example

# Create a dictionary, using tuples as keysmulti_key_dict = {
    (1, 'a'): 'value1',
    (2, 'b'): 'value2',
    (3, 'c'): 'value3'
}
 
# Search valueskey = (2, 'b')
value = multi_key_dict.get(key)
print(f"The value for key {key} is {value}")
 
# Insert new valuemulti_key_dict[(4, 'd')] = 'value4'
print(multi_key_dict)
 
# Update valuemulti_key_dict[(1, 'a')] = 'new_value1'
print(multi_key_dict)

(2) Output

The value for key (2, 'b') is value2
{(1, 'a'): 'new_value1', (2, 'b'): 'value2', (3, 'c'): 'value3', (4, 'd'): 'value4'}
{(1, 'a'): 'new_value1', (2, 'b'): 'value2', (3, 'c'): 'value3', (4, 'd'): 'value4'}

2. Method 2: Use nested dictionaries

For more complex scenarios, we can use nested dictionaries to organize the data.

(1) Code Example

# Create a nested dictionarynested_dict = {
    1: {'a': 'value1_a', 'b': 'value1_b'},
    2: {'a': 'value2_a', 'c': 'value2_c'},
    3: {'b': 'value3_b', 'c': 'value3_c'}
}
 
# Search valuesprimary_key = 2
secondary_key = 'a'
value = nested_dict.get(primary_key, {}).get(secondary_key)
print(f"The value for keys {primary_key} and {secondary_key} is {value}")
 
# Insert new valueprimary_key_new = 4
secondary_key_new = 'd'
value_new = 'value4_d'
if primary_key_new not in nested_dict:
    nested_dict[primary_key_new] = {}
nested_dict[primary_key_new][secondary_key_new] = value_new
print(nested_dict)
 
# Update valuenested_dict[1]['a'] = 'new_value1_a'
print(nested_dict)

(2) Output

The value for keys 2 and a is value2_a
{1: {'a': 'new_value1_a', 'b': 'value1_b'}, 2: {'a': 'value2_a', 'c': 'value2_c'}, 3: {'b': 'value3_b', 'c': 'value3_c'}, 4: {'d': 'value4_d'}}
{1: {'a': 'new_value1_a', 'b': 'value1_b'}, 2: {'a': 'value2_a', 'c': 'value2_c'}, 3: {'b': 'value3_b', 'c': 'value3_c'}, 4: {'d': 'value4_d'}}

3. Method 3: Use

For scenarios where new keys need to be inserted frequently,The code can be simplified.

(1) Code Example

from collections import defaultdict
 
# Create a nested defaultdictnested_defaultdict = defaultdict(lambda: defaultdict(str))
 
# Insert valuenested_defaultdict[1]['a'] = 'value1_a'
nested_defaultdict[2]['b'] = 'value2_b'
nested_defaultdict[3]['c']['d'] = 'value3_c_d'  # Note here we have created a deeper nesting 
# Search valuesprimary_key = 2
secondary_key = 'b'
value = nested_defaultdict[primary_key][secondary_key]
print(f"The value for keys {primary_key} and {secondary_key} is {value}")
 
# Update valuenested_defaultdict[1]['a'] = 'new_value1_a'
print(nested_defaultdict)

(2) Output

The value for keys 2 and b is value2_b
defaultdict(<function <lambda> at 0x...>, {1: defaultdict(str, {'a': 'new_value1_a'}), 2: defaultdict(str, {'b': 'value2_b'}), 3: defaultdict(str, {'c': defaultdict(str, {'d': 'value3_c_d'})})})

4. Practical application and reference value

(1)Data storage: These methods are very useful when you need to store multidimensional data or objects with multiple attributes.

(2)Configuration Management: Configuration options can be organized into nested dictionaries for more convenient access and modification.

(3)cache: In a cache system, multiple keys can be used to uniquely identify cache items to avoid conflicts.

5. Things to note

(1)Uniqueness of keys: In method 1, the tuple as the key must be unique, otherwise the subsequent value will overwrite the previous value.

(2)performance:Nested dictionaries anddefaultdictPerformance during retrieval and insert operations is generally acceptable, but optimization may need to be considered when processing large amounts of data.

(3)readability: When using nested structures, the readability of the code may be reduced, so it is recommended to add appropriate comments to improve the maintainability of the code.

6. What data types are supported by Python dict as keys

In Python,dict(Dictionary) is a very flexible and powerful data structure that allows us to use key-value pairs to store and retrieve data. aboutdictThere are the following points to note for the supported key data types:

(1) Supported data types

Immutable Type

  • Integerint): Includes positive integers, negative integers and zeros. For example,{1: 'one', -2: 'two', 0: 'zero'}
  • Floating point numberfloat): Although floating point numbers can be used as keys, they are generally not recommended due to the accuracy of floating point numbers. For example,{1.0: 'one', 2.5: 'two point five'}(But pay attention to key conflicts that may result from accuracy issues).
  • Stringstr): This is one of the most commonly used key types, and a string can be a sequence of characters of any length. For example,{'apple': 'fruit', 'car': 'vehicle'}
  • Tuplestuple): Tuples are ordered sets of multiple elements, and since they are immutable, they can be used as keys for dictionaries. For example,{(1, 2): 'pair', (3, 4, 5): 'triplet'}
  • Boolean valuebool):TrueandFalseCan also be used as a key. For example,{True: 'yes', False: 'no'}
  • NoneTypeNoneCan also be used as a key. For example,{None: 'no value'}
  • frozenset: This is an immutable collection and therefore can be used as a key. For example,{frozenset([1, 2]): 'frozen set of 1 and 2'}

Custom objects of immutable types

  • If the custom class object is implemented__hash__()Methods and__eq__()Methods, and they are immutable (i.e. the state of the object will not change after creation), then such objects can also be used as keys for dictionaries.

(2) Unsupported data types

Variable Type: Since the dictionary requires that the key must be hashable, while mutable types (such as lists, collections, dictionary itself, etc.) are not hashable because their content can be changed and cannot be used as keys for dictionaries.

(3) Sample code

Here is an example of a dictionary containing multiple types of keys:

my_dict = {
    1: 'integer key',
    -3.14: 'float key',  # Note: Floating point numbers are generally not recommended as keys    'string': 'string key',
    (1, 2, 3): 'tuple key',
    True: 'boolean key',
    None: 'none key',
    frozenset([4, 5]): 'frozenset key'
}
 
# Access values ​​in the dictionaryprint(my_dict[1])         # Output: integer keyprint(my_dict[(1, 2, 3)]) # Output: tuple keyprint(my_dict[True])      # Output: boolean key 
# Try to use unsupported data types as keys (which will cause an error)# my_dict = {[1, 2]: 'list key'}  # TypeError: unhashable type: 'list'

(4) Conclusion

PythondictSupports multiple immutable types as keys, including integers, floating-point numbers (although precision issues), strings, tuples, booleans,NoneTypeandfrozensetwait. However, it does not support mutable types (such as lists, collections, dictionaries, etc.) as keys. Understanding these rules helps us to use Python's dictionary data structures more efficiently.

This is the article about the method of supporting multiple keys in Python. This is all about this article. For more related content related to Python dict supporting multiple keys, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me more in the future!