Python Dictionaries

Create and access

myDn = {"myKey1":"myValue1","myKey2":"myValue2"} # Create a dictionary print( myDn["myKey1"] ) # Display the value accessed by the specified key name myDn["myKey1"] = "a new value" # Modify the value with the specified key name
  • A dictionary is like a Map in other programming languages, you specify keys and their values, then you can access each value with its key.
  • You can use other data types, not only strings. For example the key could be an integer and the value could be a float.
  • The same dictionary doesn't have to have all keys of the same type, or all values of the same type.

Add a new key-value pair

myDn["myNewKey"] = "myNewValue"
  • If the specified key doesn't already exist, it will add it. Otherwise it will replace its value with this one.

Delete a key-value pair

del( myDn["myKey1"] )

Delete all key-value pairs

myDn.clear()

Check for a key

if myKey1 in myDn: # Code to perform

Loop though keys

for x in myDn.keys(): print(x)

Loop though values

for x in myDn.values(): print(x)
  • You can also get both keys and values as a tuple by using the .items() function.

Combine dictionaries

myDn.update({"myKey1":"updatedVal", "myAddedKey":"Added Value"})
  • If a key is already there, the value will be updated to the new value; otherwise the key-value pair will be added as a new entry.
  • If you have an existing dictionary, you can pass that as a parameter to the update function rather than defining a new one.

Get a copy

myNewDn = myDn.copy()
  • This gets a new dictionary with the same key-value pairs, it will not be changed by changing the original.

Challenge

Create a report card dictionary that has six entries, each with a course name as the key and a numeric score as the value. Combine it with a dictionary that has two different courses as well as one course that is the same but with a new grade. Then loop through all of the entries, displaying the course and grade for each.

Completed