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 .

python - Why dict.get(key) instead of dict[key]? - Stack Overflow

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]

Dyktowanie i plik w Pythonie  |  Python Education  |  Google for Developers

20 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

13 Likes

I got same question about the difference

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

2 Likes

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.

95 Likes

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.

15 Likes

.keys() creates a <class ‘dict_keys’>. Here we can not use any list methods such as .append to update this data type.

list() creates a <class ‘list’ >. Voilà!, you may play around with whatever methods you like to for the list data type.

1 Like

I think the poster was asking about the .keys() method vs list function for viewing all of the keys present in a dictionary. I don’t think they mentioned .get().

i just love people who explain things in plane english makes me cry :heart_eyes:

very good explaination did not even use one transistors in my cpu lol

simple and direct answer! tks :slightly_smiling_face:

So , they definetly have to enclude this important thingh in the lesson . https://www.codecademy.com/courses/learn-python-3/lessons/using-dictionaries/exercises/get-all-keys. What do exactly means a key_object .
Appearently , a KEY_OBJECT is kind an interactive object which channges even if we .updates the dict in the next row

Hello anoop.jv7,

Thank you for your awesome question! :slightly_smiling_face:


  • list(dict_name) = Mutable

    • Can be modified like the lists that one uses regularly in Python
  • dict_name.keys() = Immutable

    • Cannot be modified (e.g. can be used to print to terminal)

I hope this helps! :star2: Thank you for reading! :grin:

Thanks. one of the best explanation i’ve read for the difference btwn list and dict