Python Language Dictionary Accessing keys and values


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:

# Python2: ['a', 'b']
# Python3: dict_keys(['b', 'a'])

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

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

# 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.