Python - Dictionary keys and values


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:


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


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.


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


Related Topics