Python - Dictionary keys and values

Introduction

For instance, the dictionary values and items methods return all of the dictionary's values and (key,value) pair tuples, respectively.

Along with keys, these are useful in loops to step through dictionary entries one by one.

As for keys, these two methods return iterable objects in 3.X, so wrap them in a list call there to collect their values all at once for display:

Demo

D = {'test': 2, 'ham': 1, 'eggs': 3} 
print( list(D.values()) )
print( list(D.items()) )

Result

Fetching a nonexistent key is normally an error.

The get method returns a default value-None, or a passed-in default-if the key doesn't exist.

It's an easy way to fill in a default for a key that isn't present, and avoid a missing-key error.

Demo

D = {'test': 2, 'ham': 1, 'eggs': 3} 
print( D.get('test') )                          # A key that is there 
# ww  w  . j a  v  a 2 s.  c om
print(D.get('toast'))                  # A key that is missing 
print( D.get('toast', 88) )

Result

Related Topics