Reputation: 63
What is the difference between for loop in the dictionaries with .keys()
method and without .keys()
method in Python?
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for i in thisdict:
print(i)
for i in thisdict.keys():
print(i)
What is the difference?
Upvotes: 6
Views: 1107
Reputation: 4676
From the Python documentation:
keys()
Return a new view of the dictionary’s keys. See the documentation of view objects.
and from the link above:
The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
Dictionary views can be iterated over to yield their respective data, and support membership tests [...]
Without keys()-method, you have simply an iterator over the keys available (which is probably preferred), as you can see here (same as second, but without loading and calling keys method):
In [1]: import dis
In [2]: dis.dis("for i in {None: None}: print(i)")
1 0 LOAD_CONST 0 (None)
2 LOAD_CONST 0 (None)
4 BUILD_MAP 1
6 GET_ITER
>> 8 FOR_ITER 12 (to 22)
10 STORE_NAME 0 (i)
12 LOAD_NAME 1 (print)
14 LOAD_NAME 0 (i)
16 CALL_FUNCTION 1
18 POP_TOP
20 JUMP_ABSOLUTE 8
>> 22 LOAD_CONST 0 (None)
24 RETURN_VALUE
In [3]: dis.dis("for i in {None: None}.keys(): print(i)")
1 0 LOAD_CONST 0 (None)
2 LOAD_CONST 0 (None)
4 BUILD_MAP 1
6 LOAD_METHOD 0 (keys)
8 CALL_METHOD 0
10 GET_ITER
>> 12 FOR_ITER 12 (to 26)
14 STORE_NAME 1 (i)
16 LOAD_NAME 2 (print)
18 LOAD_NAME 1 (i)
20 CALL_FUNCTION 1
22 POP_TOP
24 JUMP_ABSOLUTE 12
>> 26 LOAD_CONST 0 (None)
28 RETURN_VALUE
If you only want to iterate over the keys of a dictionary, there is no need to call keys()-method which gives you the dynamic view on the dictionary’s entries.
Upvotes: 5
Reputation: 100
The keys() method returns a set-like object, which can be useful for calculating intersections with other dictionaries and so on. In your case, as you're just iterating, there is no practical difference at all.
Upvotes: 2