Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. dictionaries
6 min read

Dictionaries

A Python dictionary works like a map or hash table in other languages: it holds key-value pairs. Python uses curly braces ({}) to denote dictionaries. Its default constructor is dict().

When displaying dictionaries, values are written in the form <key>: <value>. If there are multiple values in the dictionary, key-value pairs are comma-separated.

CRUD Operations

CRUD (Create, Read, Update, Delete) are the four basic operations for item storage.

C: Creating Entries

Creating entries can be done using square brackets ([]). Pass the key into the square brackets and assign this as the value.

python
1course = dict()
2course["name"] = "Cybersecurity"    # course = {"name": "Cybersecurity"}

It is important to note that if that key is already in the dictionary, it will overwrite the current value with the new value. See Updating Entries for more information.

R: Reading Entries

To access items in the dictionary, you can use square brackets and pass the key as the argument. However, if the key is not in the dictionary, this operation raises a KeyError. Here's an example:

python
1user = {"username": "echo", "name": "John Doe"}
2print(user["username"])
3

Running this code yields the following output:

echo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'wrong'

A way around this is to use the dict.get() method. This is discussed in the Functions and Methods section.

U: Updating Entries

There are two ways to update an entry: using square brackets or the update() method.

To update using square brackets, follow the same syntax as entry creation. So long as that key exists, it will update it to the new value.

python
1user = {"username": "echo", "name": "John Doe"}
2user["username"] = "alpha"    # user = {"username": "alpha", "name": "John Doe"}

Otherwise, we can use the dict.update() method to update the dictionary. This method requires another dictionary as its argument; it will replace all keys in the calling dictionary with the parameter.

python
1user = {"username": "echo", "name": "John Doe"}
2user.update({"username": "alpha"})
Info
dict.update() can also be used to create new entries. If the parameter dictionary has keys that the caller does not, those will be added as new keys.

D: Deleting Entries

When removing items from the dictionary, the del keyword is used. del removes a key from a dictionary, or removes a name entirely so it can't be used again. You can use it to delete one key or the variable holding the whole dictionary. If you attempt to delete a key that doesn't exist, Python raises a KeyError; if you attempt to delete an object that doesn't exist, Python raises a NameError.

Here is an example of how the del keyword is used:

python
1user = {"username": "echo", "name": "John Doe"}
2del user["username"]    # user = {"name": "John Doe"}
3

Functions and Methods

These built-in functions work on dictionaries the same way they work on other data structures.

SignatureDescription
len(dict)Gives the length (the number of keys)
str(dict)Produces a string representation of the dictionary
type(dict)Returns the type of the passed parameter (for dicts, dict)

Dictionaries have several very important methods for CRUD operations. Most of these methods are unique to dictionaries due to it being a key-value data structure.

SignatureDescription
dict.clear()Deletes all keys from the dictionary
dict.copy()Returns a shallow copy of the dictionary
dict.get(key, default)Returns the value at the key like dict[key], but returns default (or None) instead of raising KeyError when the key is missing
dict.items()Returns a view of (key, value) pairs, ready to unpack in a for loop
dict.keys()Returns a view of the dictionary's keys
dict.values()Returns a view of the dictionary's values
dict.update(dict2)Adds every entry from dict2, replacing existing keys
dict.pop(key, default)Removes the key and returns its value

The three views stay in sync with the dictionary as it changes. Wrap one in list() if you need a real list, for example to index into it.

Since Python 3.7, dictionaries remember insertion order: iterating over one yields keys in the order they were first added.

Dictionary Restrictions

There are no restrictions on dictionary values. Dictionary keys, however, have two important rules, because of how the dictionary finds them.

  1. Duplicate keys are not allowed. When encountering duplicate keys, the last assignment prevails:
python
my_dict = {'Name': 'Lara', 'Age': 7, 'Name': 'Manni'}    # dict["Name"] = "Manni"
  1. Keys must be hashable. The dictionary stores each key by its hash, so a key's value can never change. In practice this means immutable types: strings, numbers, and tuples of those. Using a list or another dictionary as a key raises a TypeError.
python
my_dict = {['Name']: 'Lara', 'Age': 7}    # TypeError: unhashable type: 'list'

JSON Data

JavaScript Object Notation, or JSON, is a text format for storing and transmitting data. Its objects map directly onto Python dictionaries.

json
1{
2  "employee": {
3    "name": "sonoo",
4    "salary": 56000,

Python has the json module for processing JSON, most often from files with the .json suffix. Reading files is covered in File I/O. The json.loads() method converts JSON inside a string to a dictionary. Here's an example:

python
1import json
2
3employee = json.loads('{"employee": {"name": "sonoo", "salary": 56000, "married": true}}')
4employee["employee"]["salary"]    # Return: 56000

To read straight from an open file, use json.load() instead.

python
1import json
2
3with open("employee.json") as f:
4    employee = json.load(f)

Using json.dumps(), we can convert a dictionary back into a JSON string. Notice that Python's True becomes JSON's true:

python
1print(json.dumps(employee))
2# Console: {"employee": {"name": "sonoo", "salary": 56000, "married": true}}

In the same way, we use json.dump() for writing to a file opened for writing:

python
1with open("copy.json", "w") as f:
2    json.dump(employee, f)    # alternatively, f.write(json.dumps(employee))
Success
It might be beneficial to think of json.dumps() and json.loads() as "Dump String" and "Load String". That way, they aren't as easily confused with json.dump() and json.load().
print
(
user
[
"wrong"
]
)
# user = {"username": "alpha", "name": "John Doe"}
del
user
# the user object no longer exists
4print("User:", user) # throws NameError: name 'user' is not defined
5
"married"
:
true
6 }
7}