A Python dictionary is an unordered, mutable sequence whose elements are stored in the form of "key-value". In contrast, lists and tuples are ordered sequences, and their elements are stored next to each other at the bottom.
The dictionary type is the only mapping type in Python. "Mapping" is a term in mathematics. To understand it in simple form, it refers to the corresponding relationship between elements, that is, through one element, the other element can be found uniquely.
In the dictionary, it is customary to refer to the index corresponding to each element as a key, the element corresponding to each key as a value, and the key and its associated value as a "key-value pair."
In general, the main characteristics of dictionary types are shown in the following table.
Main Features | Explanation |
---|---|
Reading elements by key instead of by index | Dictionary types are sometimes called associative arrays or hashes. It is a series of values linked by key, so you can get the specified item from the dictionary by key, but not by index. |
Dictionary is an unordered collection of any data type | Unlike lists and tuples, the element corresponding to index 0 is usually called the first element, while the elements in the dictionary are out of order. |
Dictionaries are mutable and can be arbitrarily nested | The dictionary can be grown or shortened in place (no need to generate a copy), and it supports any depth of nesting, that is, the value stored in the dictionary can also be a list or other dictionary. |
The keys in the dictionary must be unique | The dictionary does not support multiple occurrences of the same key, otherwise only the last key-value pair will be retained. |
The keys in the dictionary must be immutable | The values in the dictionary are immutable. You can only use numbers, strings, or tuples. You cannot use lists. |
Like lists and tuples, dictionary have their own types. In Python, the data type of a dictionary is dict, which can be viewed through the type function:
a = {'Jason': 18, 'Nicole': 27, 'Peter': 3} #a is a dictionary type type(a)
The output is:
dict
There are many ways to create a dictionary.
Since each element in the dictionary contains two parts, namely the key and the value, when creating the dictionary, use a colon: to separate the keys and values, and use a comma to separate the adjacent elements. All Elements are enclosed in braces {}.
The syntax for creating a dictionary using {} is as follows:
dictname = {'key': 'value1', 'key2': 'value2', ..., 'keyn': valuen}
Where:
Note that each key in the same dictionary must be unique and cannot be repeated.
The following code demonstrates creating a dictionary using curly brace syntax:
#Use string as key age = {'Jason': 18, 'Nicole': 27, 'Peter': 3} print (age) #Using tuples and numbers as keys dict_1 = {('Jason', 'Nicole'): 88, 55: [9,8,7]} print (dict_1) #Create empty tuple dict_2 = () print (dict_2)
The output is:
{'Jason': 18, 'Nicole': 27, 'Peter': 3}
{('Jason', 'Nicole'): 88, 55: [9, 8, 7]}
()
You can see that the keys of the dictionary can be integers, strings, or tuples, as long as they meet the unique and immutable characteristics; the values of the dictionary can be any data type supported by Python.
In Python, you can also use the fromkeys () method provided by the dictionary type to create a dictionary with default values in the following format:
dictname = dict.fromkeys (list, value = None)
Among them, the list parameter represents a list of all the keys in the dictionary (list); the value parameter represents the default value, or null if not written.
Consider the following example:
knowledge = {'Language', 'Mathematics', 'English'} scores = dict.fromkeys (knowledge, 60) print (scores)
The output is:
{'Language': 60, 'English': 60, 'Mathematics': 60}
As you can see, all the elements in the knowledge list are used as the keys of the scores dictionary, and the value of each key is 60. This method of creation is usually used to initialize the dictionary and set the default value of value.
There are many ways to create a dictionary through the dict function. The following table lists several commonly used methods. They all create the same dictionary a.
Create Format | Precautions |
---|---|
a = dict(str1=value1, str2=value2, str3=value3) | str represents a string type key, and value represents the value corresponding to the key. When creating a dictionary using this method, strings cannot be quoted. |
#Method 1 demo = [('two', 2), ('one', 1), ('three', 3)] #Method 2 demo = [['two', 2], ['one', 1], ['three', 3]] #Method 3 demo = (('two', 2), ('one', 1), ('three', 3)) #Method 4 demo = (['two', 2], ['one', 1], ['three', 3]) a = dict (demo) |
Pass a list or tuple to the dict function, and each of these elements is a list or tuple of 2 elements, with the first element as the key and the second element as the value. |
keys = ['one', 'two', 'three'] #can also be a string or tuple values = [1, 2, 3] # can also be a string or tuple a = dict (zip (keys, values)) |
By applying the dict function and the zip function, the first two lists can be converted into corresponding dictionaries. |
Note that no matter which way to create a dictionary, the keys of each element in the dictionary can only be strings, tuples or numbers, not lists. Lists are mutable and cannot be used as keys.
If no parameters are passed to the dict function, it means creating an empty dictionary, for example:
# Create empty dictionary d = dict () print (d)
The output is:
{}
Lists and tuples access elements by subscripts. Unlike dictionaries, they access the corresponding values by keys. Because the elements in the dictionary are out of order and the position of each element is not fixed, the dictionary cannot access multiple elements at once in a sliced manner like lists and tuples.
The specific format for accessing dictionary elements in Python is:
dictname [key]
Where:
Note that the key must exist, otherwise an exception will be thrown.
Consider the following example:
tup = (['three', 56], ['ten', 88], ['five', 100], ['nine',-59]) dic = dict (tup) print (dic ['five']) #Key exists print (dic ['one']) #Key does not exist
The output is:
100
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
[ipython-input-100-de9aa00746a3] in [module]
2 dic = dict (tup)
3 print (dic ['five']) #Key exists
----> 4 print (dic ['one']) #Key does not exist
KeyError: 'one'
In addition to the above method, Python recommends using the get method provided by the dict type to get the value corresponding to the specified key. When the specified key does not exist, the get method does not throw an exception.
The syntax of the get method is:
dictname.get (key [, default])
Where:
Example:
a = dict (three = 0.75, two = 68, one = 99, nine = -58) print (a.get ('one'))
The output is:
99
Note that when the key does not exist, get returns the null value None. If you want to explicitly prompt the user that the key does not exist, you can manually set the second parameter of get, for example:
a = dict (three = 0.75, two = 68, one = 99, nine = -58) print (a.get ('five', 'The key does not exist'))
The output is:
The key does not exist
As with deleting lists and tuples, manually deleting the dictionary can also use the del keyword, for example:
a = dict (three = 0.75, two = 68, one = 99, nine = -58) print (a) del a print (a)
The output is:
{'three': 0.75, 'two': 68, 'one': 99, 'nine': -58}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
[ipython-input-103-1f9a48b3b040] in [module]
2 print (a)
3 del a
----> 4 print (a)
NameError: name 'a' is not defined
Python's built-in garbage collection function will automatically destroy unused dictionaries, so generally you don't need to manually delete through del.
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises