How dictionary works in python
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Dictionaries in Python Show
Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects. Here’s what you’ll learn in this tutorial: You’ll cover the basic characteristics of Python dictionaries and learn how to access and manage dictionary data. Once you have finished this tutorial, you should have a good sense of when a dictionary is the appropriate data type to use, and how to do so. Dictionaries and lists share the following characteristics:
Dictionaries differ from lists primarily in how elements are accessed:
Defining a DictionaryDictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces (
The following defines a dictionary that maps a location to the name of its corresponding Major League Baseball team: >>> Dictionary Mapping Location to MLB TeamYou can also construct a dictionary with the built-in
>>>
If the key values are simple strings, they can be specified as keyword arguments. So here is yet another way to define >>>
Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list. All three of the definitions shown above appear as follows when displayed: >>>
The entries in the dictionary display in the order they were defined. But that is irrelevant when it comes to retrieving them. Dictionary elements are not accessed by numerical index: >>>
Perhaps you’d still like to sort your dictionary. If that’s the case, then check out Sorting a Python Dictionary: Values, Keys, and More. Accessing Dictionary ValuesOf course, dictionary elements must be accessible somehow. If you don’t get them by index, then how do you get them? A value is retrieved from a dictionary by specifying its corresponding key in square brackets ( >>>
If you refer to a key that is not in the dictionary, Python raises an exception: >>>
Adding an entry to an existing dictionary is simply a matter of assigning a new key and value: >>>
If you want to update an entry, you can just assign a new value to an existing key: >>>
To delete an entry, use the >>>
Begone, Seahawks! Thou art an NFL team. Dictionary Keys vs. List IndicesYou may have noticed that the interpreter raises the same exception, >>>
In fact, it’s the same error. In the latter case, You will see later in this tutorial that an object of any immutable type can be used as a dictionary key. Accordingly, there is no reason you can’t use integers: >>>
In the expressions >>>
The syntax may look similar, but you can’t treat a dictionary like a list: >>>
Building a Dictionary IncrementallyDefining a dictionary using curly braces and a list of key-value pairs, as shown above, is fine if you know all the keys and values in advance. But what if you want to build a dictionary on the fly? You can start by creating an empty dictionary, which is specified by empty curly braces. Then you can add new keys and values one at a time: >>>
Once the dictionary is created in this way, its values are accessed the same way as any other dictionary: >>>
Retrieving the values in the sublist or subdictionary requires an additional index or key: >>>
This example exhibits another feature of dictionaries: the values contained in the dictionary don’t need to be the same type. In Just as the values in a dictionary don’t need to be of the same type, the keys don’t either: >>>
Here, one of the keys is an integer, one is a float, and one is a Boolean. It’s not obvious how this would be useful, but you never know. Notice how versatile Python dictionaries are. In You can use dictionaries for a wide range of purposes because there are so few limitations on the keys and values that are allowed. But there are some. Read on! Restrictions on Dictionary KeysAlmost any type of value can be used as a dictionary key in Python. You just saw this example, where integer, float, and Boolean objects are used as keys: >>>
You can even use built-in objects like types and functions: >>>
However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once. You saw above that when you assign a value to an already existing dictionary key, it does not add the key a second time, but replaces the existing value: >>>
Similarly, if you specify a key a second time during the initial creation of a dictionary, the second occurrence will override the first: >>>
Begone, Timberwolves! Thou art an NBA team. Sort of. Secondly, a dictionary key must be of a type that is immutable. You have already seen examples where several of the immutable types you are familiar with—integer, float, string, and Boolean—have served as dictionary keys. A tuple can also be a dictionary key, because tuples are immutable: >>>
(Recall from the discussion on tuples that one rationale for using a tuple instead of a list is that there are circumstances where an immutable type is required. This is one of them.) However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable: >>>
Restrictions on Dictionary ValuesBy contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials. There is also no restriction against a particular value appearing in a dictionary multiple times: >>>
Operators and Built-in FunctionsYou have already become familiar with many of the operators and built-in functions that can be used with strings, lists, and tuples. Some of these work with dictionaries as well. For example, the >>>
You can use the >>>
In the second case, due to short-circuit evaluation, the expression The >>>
Built-in Dictionary MethodsAs with strings and lists, there are several built-in methods that can be invoked on dictionaries. In fact, in some cases, the list and dictionary methods share the same name. (In the discussion on object-oriented programming, you will see that it is perfectly acceptable for different types to have methods with the same name.) The following is an overview of methods that apply to dictionaries:
|