- Dictionaries
- dict ionary cheat sheet
- Examples
- Empty dict s
- Creating dict s with items
- Side note: What can be used as keys?
- Accessing
- Adding, Removing
- Updating
- Complex Dictionaries
- Working with items , keys , and values
- 1. my_dict.keys() Getting all the keys in a dictionary
- 2. my_dict.values() Getting all the values in a dictionary.
- 3. my_dict.items() Getting all the items (key, value pairs) in a dictionary
- Get Keys and Values from a Dictionary in Python
- A Brief Anatomy of a Dictionary
- What Is a Dictionary in Python?
- Building Blocks of a Dictionary
- Python — Access Dictionary Items
- Example
- Example
- Get Keys
- Example
- Example
- Get Values
- Example
- Example
- Example
- Get Items
- Example
- Example
- Example
- Check if Key Exists
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Dictionaries
Dictionaries are a useful type that allow us to store our data in key, value pairs. Dictionaries themselves are mutable, but, dictionary keys can only be immutable types.
We use dictionaries when we want to be able to quickly access additional data associated with a particular key. A great practical application for dictionaries is memoization. Let’s say you want to save computing power, and store the result for a function called with particular arguments. The arguments could be the key, with the result stored as the value. Next time someone calls your function, you can check your dictionary to see if the answer is pre-computed.
Looking for a key in a large dictionary is extremely fast. Unlike lists, we don’t have to check every item for a match.
dict ionary cheat sheet
type | dict |
---|---|
use | Use for storing data in key, value pairs. Keys used must be immutable data types. |
creation | <> or dict() for an empty dict . for a dict with items. |
search methods | key in my_dict |
search speed | Searching for a key in a large dictionary is fast. |
common methods | my_dictPython get dictionary key and value to get the value by key , and throw a KeyError if key is not in the dictionary. Use my_dict.get(key) to fail silently if key is not in my_dict . my_dict.items() for all key, value pairs, my_dict.keys() for all keys, and my_dict.values() for all values. |
order preserved? | Sort of. As of Python 3.6 a dict is sorted by insertion order. Items can’t be accessed by index, only by key. |
mutable? | Yes. Can add or remove keys from dict s. |
in-place sortable? | No. dict s don’t have an index, only keys. |
Examples
Empty dict s
We already learned one of the methods of creating an empty dict when we tried (and failed) to create an empty set with <> . The other way is to use the dict() method.
>>> my_dict = <> >>> type(my_dict) >>> my_dict = dict() >>> type(my_dict)
Creating dict s with items
If we want to create dict s with items in them, we need to pass in key, value pairs. A dict is declared with curly braces <> , followed by a key and a value, separated with a colon : . Multiple key and value pairs are separated with commas , .
We can call familiar methods on our dictionary, like finding out how many key / value pairs it contains with the built-in len(my_dict) method.
Side note: What can be used as keys?
Any type of object, mutable or immutable, can be used as a value but just like set s, dict ionaries can only use immutable types as keys. That means you can use int , str , or even tuple as a key, but not a set , list , or other dict ionary.
You’ll see a TypeError: unhashable type: ‘list’ if you try to use a mutable type, like a list as a dict ionary key.
>>> my_dict = <[]: 1>Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'
Accessing
Our dict contains key , value pairs. Because a dict ionary isn’t ordered, we can’t access the items in it by position. Instead, to access the items in it, we use square-bracket my_dictPython get dictionary key and value notation, similar to how we access items in a list with square bracket notation containing the position.
>>> nums = >>> nums[1] 'one' >>> nums[2] 'two'
Q: What happens when we try to access a key in a dict ionary with square bracket notation, but the key isn’t present?
We’ll get a KeyError: key if we try to access my_dictPython get dictionary key and value with square bracket notation, but key isn’t in the dictionary.
>>> nums = >>> nums[4] Traceback (most recent call last): File "", line 1, in KeyError: 4
One way to get around this is to use the my_dict.get(key) method. Using this method, if the key isn’t present, no error is thrown, and no value (aka the None type) is returned.
>>> nums = >>> nums.get(4) >>> result = nums.get(4) >>> type(result)
If we want to provide a default value if the key is missing, we also pass an optional argument to the my_dict.get(key) method like so: my_dict.get(key, default_val)
>>> nums = >>> nums.get(4, "default") 'default'
Adding, Removing
To add a new key value pair to the dictionary, you’ll use square-bracket notation.
If you try to put a key into a dictionary that’s already there, you’ll just end up replacing it. To avoid subtle bugs, you can check if a particular key is in a dictionary with the in keyword. We’ll cover that technique in Chapter 6 — Control Statements and Looping.
>>> nums = >>> nums[8] = "eight" >>> nums >>> nums[8] = "oops, overwritten" >>> nums >>> 8 in nums True
Updating
Just like with list s an set s, you can update the items in a dictionary with the items from another dictionary.
>>> colors = >>> numbers = >>> colors.update(numbers) >>> colors
Complex Dictionaries
One incredibly useful scenario for dictionaries is storing the values in a list or other sequence. Going into too much detail is outside of the scope of the class, but I’ll show you a quick example:
>>> colors = >>> colors >>> colors["Green"].append("Apples") >>> colors
Working with items , keys , and values
There are three useful methods you need to remember about dict ionary access:
1. my_dict.keys() Getting all the keys in a dictionary
>>> nums = >>> nums.keys() dict_keys([1, 2, 3, 8])
2. my_dict.values() Getting all the values in a dictionary.
>>> nums = >>> nums.values() dict_values(['one', 'two', 'three', 'eight'])
3. my_dict.items() Getting all the items (key, value pairs) in a dictionary
Notice that my_dict.items() returns a type that looks like a list. It contains two-item tuple s containing the key, value pairs.
>>> nums = >>> nums.items() dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (8, 'eight')])
Get Keys and Values from a Dictionary in Python
A dictionary in Python is an essential and robust built-in data structure that allows efficient retrieval of data by establishing a relationship between keys and values. It is an unordered collection of key-value pairs, where the values are stored under a specific key rather than in a particular order.
In this article, we will take a look at different approaches for accessing keys and values in dictionaries. We will review illustrative examples and discuss the appropriate contexts for each approach.
A Brief Anatomy of a Dictionary
What Is a Dictionary in Python?
You can visualize a Python dictionary by thinking about traditional physical dictionaries. The dictionary’s key is similar to a word that we would like to search for, and the value is like the corresponding definition of the word in the dictionary. In terms of Python’s data structures, dictionaries are containers that can hold other objects. Unlike ordered or indexed sequences (such as lists), dictionaries are mappings that assign a distinct name or key to each element.
Building Blocks of a Dictionary
A key in a dictionary serves as a unique identifier that allows us to locate specific information. Keys can be of any immutable type (e.g., strings, numbers, tuples). The data associated with each key is called a value , and can be mutable.
Any data type, such as a string, number, list, or even another dictionary, is an acceptable value . The combination of these key-value pairs is represented in the form of tuples, known as dictionary items . Together, these keys, values, and items collectively form the core structure of a dictionary. Let’s explore how we can retrieve these elements.
To illustrate this, let’s first construct a simple address book dictionary. The keys represent names of individuals, and the corresponding values contain their associated shipping addresses. We can construct it as below:
address_book = < "Alicia Johnson": "123 Main Street, Cityville", "Jerry Smith": "456 Corner Avenue, Townsville", "Michael Jonas": "789 End Lane, Villageville" >
We can visualize the structure of our simple dictionary as below:
Python — Access Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the «model» key:
There is also a method called get() that will give you the same result:
Example
Get the value of the «model» key:
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
Get Values
The values() method will return a list of all the values in the dictionary.
Example
The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets updated as well:
Example
Add a new item to the original dictionary, and see that the values list gets updated as well:
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
Example
Add a new item to the original dictionary, and see that the items list gets updated as well:
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if «model» is present in the dictionary:
thisdict = <
«brand»: «Ford»,
«model»: «Mustang»,
«year»: 1964
>
if «model» in thisdict:
print(«Yes, ‘model’ is one of the keys in the thisdict dictionary»)
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.