Dictionaries
A dictionary (or dict) is a collection of key:value pairs. As of Python version 3.7, dictionaries are now ordered by insertion order.
Creating a dictionary
Accessing values
Adding and changing keys
Dictionary Methods
Dictionaries have a lot of useful methods. Here are a few:
get
"safely" access a key and optionally set a default value
keys
gets a list of all the keys
values
gets a list of all the values
items
gets a list of key-value pairs as tuples
pop
remove a key-value pair with the specified key
Avoid errors when pop
ping a non-existent key
For more dictionary methods: https://www.w3schools.com/python/python_ref_dictionary.asp
Looping Over Dictionaries
Dictionaries are iterable with a for in
loop.
You can also loop over the lists returned by the keys
, values
, and items
methods.
Dictionary Operators
The in
membership operator works with dictionaries.
As of Python version 3.9, the |
operator can merge dictionaries.
NOTE spam
from b
overwrote the one from a
as b
is the "last-seen" value (the right-hand operand).
Last updated
Was this helpful?