The dictionary is the second major Python container after the list. In this article, I’ll introduce you to the dictionary and show you different ways you can use dictionaries for solving your computational problems using Python.

Dictionaries Defined

A dictionary is a container for storing associative data. Associative data is data that has two parts — a key and a value. Keys are like the words in a dictionary (hence the container name) and values are like definitions. So, for example, when I enter apple as a key, the value that is associated with an apple is displayed — the round fruit of a tree in the rose family.

Another way to think of a dictionary is as a container that stores mappings. For example, a state capitol maps to the state it is located in, such that California maps to Sacramento, or New York maps to Albany.

Dictionaries are used to store lots of different things, from words and definitions, to names and phone numbers, to even variable names and their values. Dictionaries, on the other hand, are not used to store data that is sequential in nature, such as a list of employee names, or a list of your grades on a test. Sequential data is best stored in a list.

Creating an Empty Dictionary and Initializing a Dictionary with Values

To create a new dictionary, Python provides the function dict. This function is called on its own when you want to declare a new dictionary. The syntax template for this function is:

dictionary-name = dict()

If I want to create a dictionary of names and phone numbers, I can write this line of code:

phoneNumbers = dict()

If I want to create a new dictionary and initialize it with some mappings, I can do this:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}

Accessing Dictionary Values

A dictionary value is accessed by providing the key using array notation or subscript notation. Here is the syntax template for accessing a dictionary value:

dictionary-name[key]

The key is places inside the brackets which follow immediately after the dictionary name.

The following program sets up the phone number dictionary from earlier and displays each number via a name:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
print("Brown's number is",phoneNumbers['Brown'])
print("Smith's number is",phoneNumbers['Smith'])
print("Jones' number is",phoneNumbers['Jones'])
print("Green's number is",phoneNumbers['Green'])

The output from this program is:

Brown's number is 2000
Smith's number is 2001
Jones' number is 2002
Green's number is 2003

Dictionary Functions and Methods

There are several Python functions you can use with dictionaries. The first of these is len, which returns the number of key/value pairs stored in a dictionary. Here is an example of this function at work:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
print("There are",len(phoneNumbers)," numbers stored in 
      phoneNumbers.")

The output is:

There are 4 numbers stored in phoneNumbers.:

The keys method can be used to create a list of all the keys in a dictionary, which you can use to iterate through the dictionary to access its values. Here’s how that works:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',|
                'Jones': '2002', 'Green': '2003'}
keys = phoneNumbers.keys()
for key in keys:
  print(key,": ",phoneNumbers[key])

The output from this program is:

Brown :  2000
Smith :  2001
Jones :  2002
Green :  2003

The in function can be used to determine if a key is found in a dictionary. Here is an example:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
key = input("Enter a name: ")
if key in phoneNumbers:
  print(key,":",phoneNumbers[key])
else:
  print(key,"does not have a number in this dictionary.")

Here are two runs of this program:

C:\python>test.py
Enter a name: Smith
Smith : 2001

C:\python>test.py
Enter a name: Bonner
Bonner does not have a number in this dictionary.

You can’t use the in function to find a value in a dictionary but instead you can create a list of values using the values method and then use in on the list. Here’s an example:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
vals = phoneNumbers.values()
number = input("Enter a phone number: ")
if number in vals:
  print(number,"is in the dictionary.")
else:
  print(number,"is not in the dictionary.")

Here is the output from two runs of this program:

C:\python>test.py
Enter a phone number: 2003
2003 is in the dictionary.

C:\python>test.py
Enter a phone number: 2010
2010 is not in the dictionary.

The get method takes a key and a default value and returns either the value associated with the key or the default value. Here is an example of how to use this method to retrieve either a value stored in a dictionary or a default telling the user that key is not in the dictionary:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
for i in range(1,4):
  name = input("Name to search for: ")
number = phoneNumbers.get(name, "Number not in dictionary")
print(name,number)

Here is the output from one run of this program:

Name to search for: Brown
Brown 2000
Name to search for: Jones
Jones 2002
Name to search for: Doe
Doe Number not in dictionary

The pop method removes a key/value pair from a dictionary based on the key passed to the method. Here is a program that demonstrates how pop works:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
for key in phoneNumbers.keys():
  print(key,":",phoneNumbers[key])
name = input("Enter name to remove: ")
phoneNumbers.pop(name)
print()
for key in phoneNumbers.keys():
  print(key,":",phoneNumbers[key])

Here is the output from one rBrown : 2000

Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003
Enter name to remove: Jones
Brown : 2000
Smith : 2001
Green : 2003

A related method, popitem, removes the last inserted key/value pair from a dictionary. Here’s an example program:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
for key in phoneNumbers.
print()
for key in phoneNumbers.keys():
  print(key,":",phoneNumbers[key])

Here is the output from this program:

Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003
Brown : 2000
Smith : 2001
Jones : 2002

The setdefault method will return the value of a given key, or if the key is not in the dictionary, put the key and a value provided as the second argument into the dictionary. The method returns either the value of the key that is already stored in the dictionary, or the method returns the new value stored with the new key.

Here is a program that demonstrates how setdefault works:

phoneNumbers = {'Brown': '2000', 'Smith': '2001',
                'Jones': '2002', 'Green': '2003'}
for key in phoneNumbers.keys():
  print(key,":",phoneNumbers[key])
name = input("Enter name: ")
number = input("Enter number: ")
value = phoneNumbers.setdefault(name, number)
for key in phoneNumbers.keys():
  print(key,":",phoneNumbers[key])

Here are two runs of this program, the first one entering a new key and the second one entering a key that already exists in the dictionary:

C:\python>test.py
Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003
Enter name: Doe
Enter number: 2004
Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003
Doe : 2004
c:\python>test.py
Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003
Enter name: Jones
Enter number: 2002
Brown : 2000
Smith : 2001
Jones : 2002
Green : 2003

#python #programming #developer #web-development #machine-learning

Learning Python Data Structures: Dictionaries
13.45 GEEK