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

dictionary["bogus"]

would raise a KeyError .

https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey

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]

https://developers.google.com/edu/python/dict-files

2 Likes

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

1 Like

I got same question about the difference

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

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.

Ex:

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)
print(users)
print(lessons)
print(lesson_lst)
num_exercises.update({"exception":3})
print(lessons)
print(lesson_lst)

Sorry for badly formatted code and no comments.