I'm writing a django application where I will get a dictionary from the user that can be of variable size. I want to have a limit for how big the dictionary can be, i.e. how many (key, value)
pairs it can hold. I want it to be no bigger than 200. I suspect that if I do:
if len(user_dict)>200:
raise ValidationError("dict has too many (key, value) pairs")
python will have to count the whole dict. If the dict is huge, because of a malicious user, this will eat unnecessary processing power. Or does the dict keep track of how many objects it holds, meaning len(user_dict)
is a simple lookup operation? What is the best way to solve this problem?
I was thinking something like:
i=0
for key in user_dict.keys():
i += 1
if i>200:
raise ValidationError("dict has too many (key, value) pairs")