Can you create a dictionary in a dictionary python?
Ngày đăng:07/10/2022
Trả lời:0
Lượt xem:189
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
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:
Both are mutable.
Both are dynamic. They can grow and shrink as
needed.
Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
Dictionaries differ from lists primarily in how elements are accessed:
List elements are accessed by their position in the list, via indexing.
Dictionary elements are accessed via keys.
Defining a
Dictionary
Dictionaries 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 ({}). A colon (:)
separates each key from its associated value:
d={<key>:<value>,<key>:<value>,...<key>:<value>}
The following defines a dictionary that maps a location to the name of its corresponding Major League Baseball team:
You can also construct a dictionary with the built-in dict() function. The argument to dict() should be a sequence of key-value
pairs. A list of tuples works well for this:
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:
>>>
>>> MLB_team[1]Traceback (most recent call last):
File "", line 1, in MLB_team[1]KeyError: 1
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 Values
Of 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 ([]):
You may have noticed that the interpreter raises the same exception, KeyError, when a dictionary is accessed with either an undefined key or by a numeric index:
>>>
>>> MLB_team['Toronto']Traceback (most recent call last):
File "", line 1, in MLB_team['Toronto']KeyError: 'Toronto'>>> MLB_team[1]Traceback (most recent call last):
File "", line 1, in MLB_team[1]KeyError: 1
In fact, it’s the same error. In the latter case, [1] looks like a numerical index, but it isn’t.
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 MLB_team[1], d[0], and d[2], the numbers in square brackets appear as though they might be indices. But they have nothing to do with the order of the items in the dictionary. Python is interpreting them as dictionary keys. If you define this same dictionary in reverse order, you still get the same values using the same keys:
The syntax may look similar, but
you can’t treat a dictionary like a list:
>>>
>>> type(d)>>> d[-1]Traceback (most recent call last):
File "", line 1, in d[-1]KeyError: -1>>> d[0:2]Traceback (most recent call last):
File "", line 1, in d[0:2]TypeError: unhashable type: 'slice'>>> d.append('e')Traceback (most recent call last):
File "", line 1, in d.append('e')AttributeError: 'dict' object has no attribute 'append'
Building a Dictionary Incrementally
Defining 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:
This example exhibits another feature of dictionaries: the values contained in the dictionary don’t need to be the same type. In person, some of the values are strings, one is an integer, one is a list, and one is another dictionary.
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 MLB_team, the same piece of information (the baseball team name) is kept for each of several different
geographical locations. person, on the other hand, stores varying types of data for a single person.
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 Keys
Almost
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:
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:
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:
>>>
>>> d={[1,1]:'a',[1,2]:'b',[2,1]:'c',[2,2]:'d'}Traceback (most recent call last):
File "", line 1, in d={[1,1]:'a',[1,2]:'b',[2,1]:'c',[2,2]:'d'}TypeError: unhashable type: 'list'
Restrictions on Dictionary Values
By 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:
You 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 in and not in operators return True or False according to whether the specified operand occurs as a key in the dictionary:
You can use the in operator together with short-circuit evaluation to avoid raising an error
when trying to access a key that is not in the dictionary:
>>>
>>> MLB_team['Toronto']Traceback (most recent call last):
File "", line 1, in MLB_team['Toronto']KeyError: 'Toronto'>>> 'Toronto'inMLB_teamandMLB_team['Toronto']False
In the second case, due to short-circuit evaluation, the expression MLB_team['Toronto'] is not evaluated, so the KeyError exception does not occur.
The len() function returns the number of key-value pairs in a dictionary:
As 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:
d.clear()
Clears a dictionary.
d.clear() empties dictionary d of all key-value pairs:
Returns the value for a key if it exists in the dictionary.
The Python dictionary .get() method provides a convenient way of getting the value of a key from a dictionary without checking ahead of time whether the key exists, and without raising an error.
d.get() searches dictionary d for and returns the associated value if it is
found. If is not found, it returns None:
If is not found and the optional argument is specified, that value is returned instead of None:
>>>
>>> print(d.get('z',-1))-1
d.items()
Returns a list of key-value pairs in a dictionary.
d.items() returns a list of tuples containing the key-value pairs in d. The first item in each tuple is the key, and the second item is the key’s value:
In this example, key 'b'
already exists in d1, so its value is updated to 200, the value for that key from d2. However, there is no key 'd' in d1, so that key-value pair is added from d2.
may also be a sequence of key-value pairs, similar to when the dict() function is used to define a dictionary. For example, can be specified as a list of tuples:
In this tutorial, you covered the basic properties of the Python dictionary and learned how to access and manipulate dictionary data.
Lists and
dictionaries are two of the most frequently used Python types. As you have seen, they have several similarities, but differ in how their elements are accessed. Lists elements are accessed by numerical index based on order, and dictionary elements are accessed by key
Because of this difference, lists and dictionaries tend to be appropriate for different circumstances. You should now have a good feel for which, if either, would be best for a given situation.
Next you
will learn about Python sets. The set is another composite data type, but it is quite different from either a list or dictionary.
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
Can I make a dictionary of dictionaries in Python?
In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.
Can a dictionary contain a dictionary?
Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
How do you initialize a dictionary in a dictionary Python?
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
Can we merge two dictionaries in Python?
In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.