Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between list(dict) and dict.keys()?

Tags:

python

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?

like image 715
lang2 Avatar asked Aug 05 '15 15:08

lang2


People also ask

What is the difference between dict and list?

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.

Should I use dict () or {}?

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.

What does dict keys () do in Python?

Python Dictionary keys() The keys() method extracts the keys of the dictionary and returns the list of keys as a view object.

What is the difference between keys () and items () in dictionary?

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.


2 Answers

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.

like image 184
Alyssa Haroldsen Avatar answered Sep 21 '22 13:09

Alyssa Haroldsen


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'>
like image 20
Pynchia Avatar answered Sep 18 '22 13:09

Pynchia