CMSC 201

Lab 12: Dictionaries

Dictionaries

dictionaries are best described as unordered “key : value” pairs where the key accesses the value. These are really useful when you want to associate one element with another like capital city to state

capState = {“Annapolis”: “Maryland”}

the first part is the key and the second is the value

It is important to note that the key must be either an immutable type or a number, so lists can not be a key. Keys must also be unique within the dictionary.

To access something in a dictionary you use its key

>>print(capState[“Annapolis”])

Maryland

to add something to a dictionary you can do

capState[“Richmond”] = “Virginia”

to loop through a dictionary

for k,v in capState.items():
 print (k, v)

will output

Richmond Virginia
Annapolis Maryland

**note dictionaries are unordered which means there is no order to how they print unless you do some manual sorting