What is a Dictionary?

Dictionaries are collections of items that have a “key” and a “value”.

Dictionaries are mutable. You do not have to reassign the dictionary to make changes to it.

They are just like lists, except instead of having an assigned index number,
you make up the index:

Example 1

testList = ["first", "second", "third"]
testDict = {0:"first", 1:"second", 2:"third"}

A dictionary in Python is enclosed by {}, and to create one you have to provide a key / value.

Each key in the dictionary must be unique.

A colon is placed between key and value (key:value)

Each key:value pair is separated by a comma

Example 2

>> phonenumbers = {'Jack':'555-555', 'Jill':'555-556'}

phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"

print phonebook
{'Jill': '555-556', 'Jack': '555-555'}

Dictionaries only work one way, to get a value out of a dictionary,you MUST enter the key.

You cannot provide the value and get the key.

Example 3

phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"

print phonebook['Jill']

Key / Value Usage

To add a key / value pair in a dictionary
>>phonebook["Matt"] = "555-557"

To change a key / value pair:
>>phonebook["Jack"] = '555-558'

To remove a key / value pair, use del
>>del phonebook["Jill"]

To see if a key exists, use has_key() method

To copy whole dictionary, use the copy() method
phonebook2 = phonebook.copy()

I mostly use dictionarys when storing results for lookups.


Leave a Reply

Your email address will not be published.