Accessing keys and values
suggest changeWhen working with dictionaries, it’s often necessary to access all the keys and values in the dictionary, either in a for loop, a list comprehension, or just as a plain list.
Given a dictionary like:
mydict = {
'a': '1',
'b': '2'
}
You can get a list of keys using the keys() method:
If instead you want a list of values, use the values() method:
If you want to work with both the key and its corresponding value, you can use the items() method:
NOTE: Since Python 3.7, keys(), values(), and items() follow insertion order. They are not sorted. Use sorted() when you need a sorted list. Dict views have no sort() method.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents