Say I have a dict:
foo = {'a': 1}
Both list(foo)
and foo.keys()
return the same thing. What's the difference between the two?
List is a collection of index values pairs as that of array in c++. Dictionary is a hashed structure of key and value pairs. The indices of list are integers starting from 0. The keys of dictionary can be of any data type.
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
Python Dictionary keys() The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
One difference is in Python 3. foo.keys()
returns an iterator of the keys, which is what foo.iterkeys()
does in Python 2, while list(foo)
returns a list of the keys.
As noted below, foo.keys()
doesn't exactly return an iterator in Python 3. It returns a dict_keys
object (or view) which, among its operations, allows iteration. You can also do fun things such as set operations and multiple iteration. It still has the concept of lazy evaluation which makes iterators so powerful.
Python3:
from the official documentation
Calling foo.keys() will return a dictionary view object. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary – it is only a view.
in fact,
type(foo.keys())
gives
<class 'dict_keys'>
whereas in Python 2 both
type(list(foo))
type(foo.keys())
give
<type 'list'>
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