Python Dictionaries

Definition

Python Dictionaries are a unordered, mutable collection of items. Python Dictionaries use a key:value format to store their items, where the key acts as a unique label assigned to that value. This key will be used when modifying, adding or removing values in a dictionary.

The items stored in a dictionary may also be other collection data types like lists, tuple’s, arrays or even another dictionaries.

here are other data types out there like arrays, tuples and lists which may be more suitable for some tasks. First scope out your problem and then decide which collection type will work the best.

Python Dictionaries Syntax

  • Dictionaries are enclosed within curly brackets
  • Have a semi colon separating their key and value items
  • Commas separating the key value pairs.
dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

Remember, Python Dictionaries are unordered collection types, hence every time you print out the while dictionary, you can expect it’s order of values to change (it’s random).

Accessing items in a Dictionary

Indexing works a bit differently in dictionaries than others collection data types. In dictionaries the key acts as the index, whereas in other collection types like lists and tuples, they are automatically indexed with numbers starting from 0.

This also means that indexes/keys in Dictionaries are not restricted to just numbers, as seen in the syntax example above.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}
print(dict["age"])
# Output
15

Adding items to a Dictionary

To add a new item into a dictionary, define a new index, and assign a value to it.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

dict["Number"] = 12345

Removing items from a Dictionary

Using the pop function

Using the pop() function we can remove an item with a specific key name. The pop() takes the key name to be removed as a parameter.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

dict.pop("Gender")

There is another type of pop function called popitem() which removes the last item inserted into the dictionary.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

dict.popitem()

Using the del function

The del keyword can be used to delete items using their key names, similar to how the pop() function works.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

dict.del["Gender"]

The del key word has the ability to delete an entire dictionary, as well as all the items contained within it.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}

del dict

Attempting to access this dictionary after it’s deleted will result in an error. Hence, use with care.

Clear Function

The clear() function empties out a dictionary, deleting all of the items within it. Unlike the del function though, it does not delete the dictionary itself.

dict = { 
  "age": "15",
  "name": "Jim",
  "Gender": "Male",
}
dict.clear()

Other Operations

Check for a specific key

dict = { "age": 15 , "name": "Jim" , "Gender": "Male" }
if "name" in dict:
     print("Found")

Finding length

dict = { "age": 15 , "name": "Jim" , "Gender": "Male" }
print(len(dict))

Iterating through a dictionary

dict = { "age": 15 , "name": "Jim" , "Gender": "Male" }
for x in dict:
      print(x) #prints out all the keys in the dictionary
dict = { "age": 15 , "name": "Jim" , "Gender": "Male" }
for x in dict:
      print(dict[x]) #prints the values of all the keys in python

Referencing

Sometimes people try to copy dictionaries by simply assigning an existing dictionary to a new variable. This results in a significant problem later on due to how Python Dictionaries work. The concept of referencing comes into play here.

For instance, dict1 = dict2, does not result in two separate entities with the same values. It results in dict2 being assigned a “reference” to dict1. What this means that any changes made to either dictionary will effect both. Below is an example of this problem’s effects.

dict = { "age": 15 , "name": "Jim" , "Gender": "Male" }
dict2 = dict
dict2["age"] = 20
print(dict)
#Output
{'age': 20, 'name': 'Jim', 'Gender': 'Male'}

As you can see, even though no changes were made to the variable dict, it’s value for the key “age” changed.

Keep in mind that you can safely assign variables to other variables if there are numbers. This problem only occurs in data types like Lists and Dictionaries. This problem is averted because numbers in Python are immutable, and a new number object is created during such operations.


Extra Example(s):

Creating a dictionary from user input.

Remember that even if you input a number, it will turn into a string as the input() function will convert anything it receives into a string. Use the int() function to get around this.

x = 0
dict = {}
while x < 3:
  key = input("Input key")
  value = input("Input value")
  dict[key] = value
  x = x + 1

print(dict)
# Output after running the program on some inputs
{'1': 'a', '2': 'b', '3': 'c'}

This marks the end of the Python Dictionaries tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments