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 (Create, Read, Update, Delete) are the four basic operations for item storage.
Creating entries can be done using square brackets ([]). Pass the key into the square brackets and assign this as the value.
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.
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:
1user = {"username": "echo", "name": "John Doe"}
2print(user["username"])
3Running 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.
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.
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.
1user = {"username": "echo", "name": "John Doe"}
2user.update({"username": "alpha"})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.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:
1user = {"username": "echo", "name": "John Doe"}
2del user["username"] # user = {"name": "John Doe"}
3These built-in functions work on dictionaries the same way they work on other data structures.
| Signature | Description |
|---|---|
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.
| Signature | Description |
|---|---|
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.
There are no restrictions on dictionary values. Dictionary keys, however, have two important rules, because of how the dictionary finds them.
my_dict = {'Name': 'Lara', 'Age': 7, 'Name': 'Manni'} # dict["Name"] = "Manni"TypeError.my_dict = {['Name']: 'Lara', 'Age': 7} # TypeError: unhashable type: 'list'JavaScript Object Notation, or JSON, is a text format for storing and transmitting data. Its objects map directly onto Python dictionaries.
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:
1import json
2
3employee = json.loads('{"employee": {"name": "sonoo", "salary": 56000, "married": true}}')
4employee["employee"]["salary"] # Return: 56000To read straight from an open file, use json.load() instead.
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:
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:
1with open("copy.json", "w") as f:
2 json.dump(employee, f) # alternatively, f.write(json.dumps(employee))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().