Python Language Dictionary Accessing keys and values

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

When 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:

print(mydict.keys())
# Python2: ['a', 'b']
# Python3: dict_keys(['b', 'a'])

If instead you want a list of values, use the values() method:

print(mydict.values())
# Python2: ['1', '2']
# Python3: dict_values(['2', '1'])

If you want to work with both the key and its corresponding value, you can use the items() method:

print(mydict.items())
# Python2: [('a', '1'), ('b', '2')]
# Python3: dict_items([('b', '2'), ('a', '1')])

NOTE: Because a dict is unsorted, keys(), values(), and items() have no sort order. Use sort(), sorted(), or an OrderedDict if you care about the order that these methods return.

Python 2/3 Difference: In Python 3, these methods return special iterable objects, not lists, and are the equivalent of the Python 2 iterkeys(), itervalues(), and iteritems() methods. These objects can be used like lists for the most part, though there are some differences. See PEP 3106 for more details.



Got any Python Language Question?