I was wondering if Python had a limit on the length of a dictionary key.
For clarification, I'm not talking about the number of keys, but the length of each individual key. I'm going to be building my dictionaries based on dynamic values (after validation), but I'm not sure if I should be taking length into account in this case.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
To determine how many items (key-value pairs) a dictionary has, use the len() method.
These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.
This answer may give the correct "final" answer (yes, spaces are allowed in dictionary key strings), but the reasoning is incorrect. The reason that spaces are allowed inside dictionary key strings has nothing to do with a style guide.
There is no such limit in place regarding dictionary keys. Since python also has arbitrary precision on numeric types, the only limit you will encounter, string or otherwise, is that of available memory. You can see another post here for a discussion on maximum string length in python 2.
Here's a bit of sample code:
from string import ascii_letters from random import choice def make_str(length): return "".join(choice(ascii_letters) for i in range(length)) test_dict = {make_str(10000000): i for i in range(5)}
Conclusion: Python will quite happily use a 10-million-character string as a dict key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With