Skip to content
Advertisement

is these two dictonary statments are same while looping it in for loop?

I read that my_dict.keys() returns the dynamic view to iterate over the dictionary. I usually iterate the dictionary without the keys() function.

So my question is, are below two code blokes are same? if not, what performance differences do these two have (which one is more optimized)

JavaScript
JavaScript

Note: I usually use python version 3.7+ so if there’s any version-wise implementation difference, kindly attach resources that I can refer to.

Advertisement

Answer

It sounds like for key in my_dict is slightly faster… try:

JavaScript

Which is what I’d expect because for key in my_dict.keys(): involves one more method call.


Edit: it appears I’ve used a crude method (time.time()) for the measurements as @ShadowRanger pointed out. See his insightful answer and comments. Also, apologies for referring to an outdated documentation.

A better approach would be using timeit which would show the results in both cases are almost identical as pointed out in @ShadowRanger’s answer, confirming other observations in the comments.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement