Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Dictionaries have a key length limit?

Tags:

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.

like image 331
pferate Avatar asked Mar 17 '14 20:03

pferate


People also ask

How many keys can a dictionary have?

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.

Do dictionaries have Len?

To determine how many items (key-value pairs) a dictionary has, use the len() method.

What Cannot be a dictionary key?

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.

Can a key in a dictionary have a space?

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.


2 Answers

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.

like image 191
Brian Avatar answered Sep 20 '22 15:09

Brian


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.

like image 39
Hugh Bothwell Avatar answered Sep 17 '22 15:09

Hugh Bothwell