Is there a difference between accessing keys with `.keys()` or `list()`?

In general, what is the difference in accessing keys via dict_name.keys() and list(dict_name). when we iterate through either, the outcome is same. Is there a performance difference? Is there advantage in using .keys() over list.
for eg.
#using .keys()
for x in dict_name.keys()
#using list
for x in list(dict_name)

It allows you to provide a default value if the key is missing:

dictionary.get("bogus", default_value)

returns default_value (whatever you choose it to be), whereas


would raise a KeyError .

Not to mention, sorting…

Common case – loop over the keys in sorted order,
accessing each key/value

   for key in sorted(dict.keys()):
    print key, dict[key]


for keys you let the dict create the data structure, while if you convert it into a list you’re forcing a list to be created. keys may be doing something requiring less work, perhaps even no work at all
if you need a list sure go ahead and convert, but otherwise use what’s already there
if all you need is to iterate, then, the reason you can convert to list that way is that a dict is iterable, so maybe what that should really say is just the dict itself with no methods or other types involved


I got same question about the difference

I am not really understand what are you mean? Can you explain it in more detail?

1 Like

The main diff is that .keys() method is a view of the dictionary object. That means when you update the dictionary, the object dict_keys will shows the updated value.

If you use the list then the list will create a snapshot of keys present at the time of assignment and it will not be in sync with dictionary updates.


user_ids = {"teraCoder": 100019, "pythonGuy": 182921, "samTheJavaMaam": 123112, "lyleLoop": 102931, "keysmithKeith": 129384}
num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
users = user_ids.keys()
lessons = num_exercises.keys()
lesson_lst = list(num_exercises)

Sorry for badly formatted code and no comments.


thanks, very insightfull!

This should be top answer. Not sure answers above are for this (keys vs list) question…

The difference is that keys() is a view object and reflects state of dictionary even if dictionary is updated. The list() function creates a list that does not update with the source dictionary.

1 Like