Python Dictionary Methods Examples


Dictionaries are a very valuable tool in Python. A dictionary is like a list, but it allows you to store data with a keyword attached as a matched pair with the data. Earlier in this book, I talked about the need for registration information in an imaginary program. The information that is needed would be:

First Name, Last Name, Address, City, State, Postal Code

A dictionary allows us to keep that information very easily. For each piece of data we have a key that is associated with it. The structure of the key/value pair is:
Each key within a dictionary must be unique, but the value may be repeated if needed. Curly brackets are used to set up the dictionary. Keys may be strings or numbers.

dict = {"Fname":"Jack","LName":"Sprat"}

You can create a blank dictionary by simply assiging a variable to an empty set of curly brackets.

Names = {}

You can add new key/value pairs to a dictionary.

>>> names = {'fname':'Fred','lname':'Frackel','city':'Aurora','state':'CO'}>>> names['phone'] = '222-222-2222'
>>> names
{'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred','phone':'222-222-2222'}

To iterate (walk through) a dictionary you can use the .iteritems() built in function. Notice that dictionaries do not store the key/value pairs in any predefined order, so items might not appear in the order that it is entered:

>>> names = {'fname':'Fred','lname':'Frackel','city':'Aurora','state':'CO'}
>>> for key,value in names.iteritems():
... print key,value
lname Frackel
city Aurora
state CO
fname Fred

Dictionary Functions

Dictionaries have the following built-in functions.


Returns the number of items in a dictionary.

>>> d = {'lname':'Frackel','fname':'Fred','city':'Aurora','state':'CO'}
>>> len(d)


Creates a dictionary from a list provided and the list must contain at least one two element tuple. The first element in the tuple is the key and the second is the value.

>>> d2 = dict([('one',1),('two',2),('three',3)])
>>> d2
{'three': 3, 'two': 2, 'one': 1}


Dictionary Methods

Dictionaries have the following built-in methods:

.clear( )

Removes all items from a dictionary.

>>> test = {'one':'1','two':'2','three':'3'}
>>> test
{'three': '3', 'two': '2', 'one': '1'}
>>> test.clear()
>>> test

.copy( )

To make a copy of a dictionary, use the .copy() method. This is a shallow copy, which means that the content of the dictionary is not copied directly by value, but by reference and points to the actual original dictionary.

>>> first = {'a':1,'b':2,'c':3}
>>> clone = first.copy()
>>> first
{'a': 1, 'b': 2, 'c': 3}
>>> clone
{'a': 1, 'b': 2, 'c': 3}


Returns a single value by key from a dictionary. Unlike the .pop() method, this does not remove the key/value pair from the dictionary. If key does not exist in dictionary, value from the optional default parameter is returned. If default is not given, returns None.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':
'Fred', 'phone':'222-222-2222'}
>>> names
{'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred','phone':'222-222-2222'}
>>> names.get('lname')

Returns True if the key exists in the dictionary. This method has been depreceated and the suggested way to check is to use key in d.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':
'Fred', 'phone':'222-222-2222'}
>>> names.has_key('city')
>>> names.has_key('address')

.items( )
Returns a list of all key/value pairs in a dictionary. Notice that this is a nonsorted list and is not in the order that the data was entered.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':'Fred', 'phone':'222-222-2222'}
>>> names.items()
[('lname', 'Frackel'), ('city', 'Aurora'), ('state', 'CO'), ('fname','Fred'), ('phone', '222-222-2222')]

.keys( )

To get a list of keys from a dictionary, use the built in function .keys(). Notice that this is a nonsorted list and is not in the order that the keys were entered.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':'Fred'}
>>> names.keys()
['lname', 'city', 'state', 'fname']

To get a list of keys from a dictionary that is sorted, assign the return values from the .keys() function to a list then apply the .sort() function to that variable.

>>> names={'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':'Fred'}
>>> namekeys = names.keys()
>>> namekeys.sort()
>>> namekeys
['city', 'fname', 'lname', 'state']

Removes and returns the value of an item in the dictionary based on the key provided. If default is not given and the key does not exist, a KeyError is raised.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname':'Fred','address':'123 Main Street'}
>>> names.pop('address')
'123 Main Street'
>>> names
{'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred','phone':'222-222-2222'}

Returns a value from the supplied key, if it exists. If not, it enters the key as a new item with the supplied default value.

>>> d1
{'a': 1, 'c': 3, 'b': 2, 'e': 0, 'd': 4}
>>> d1.setdefault('c',6)
>>> d1.setdefault('f',6)
>>> d1
{'a': 1, 'c': 3, 'b': 2, 'e': 0, 'd': 4, 'f': 6}


Updates the dictionary with the key/value pair provided in other. This will overwrite
existing keys. Returns None. The other parameter can be either a tuple or list providing
the key/value pair(s), or another dictionary.

>>> names = {'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred'}
>>> names.update({'address':'123 Main Street'})
>>> names
{'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred','phone':'222-222-2222', 'address': '123 Main Street'}


.values( )
Returns a list of all values in a dictionary. The list returned is unsorted and may not be in the order that the data was entered. Using the list after the above update:

>>> names
{'lname': 'Frackel', 'city': 'Aurora', 'state': 'CO', 'fname': 'Fred','phone':'222-222-2222'}
>>> names.values()
['Frackel', 'Aurora', 'CO', 'Fred', '222-222-2222']


In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.