An overview of the dictionary :
A dictionary is a A disorderly , Sure Modified , Elemental presentation Key value pair In the form of , With Comma split Of , With Surrounded by braces Data type of ;
A dictionary is the same as a list , Can store multiple data , But there is no special order of values in the dictionary ; In the list , When looking for an element , By subscript , But if there are many subscripts , It is inconvenient to find elements , Then you need to use a dictionary .
Each element of the dictionary consists of two parts , key : value . for example :‘name’:‘hu’ , name As the key ,hu Value .
The dictionary is Python The only basic data type The mapping relationship Data type of ;
Let's define a dictionary first :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
In the dictionary of definitions , Each key corresponds to a corresponding value , Are keys and values only one-to-one ? You can try to see :
message = {
'name':'jake','hu','age':19,'love':'kongfu'}# Key in name Followed by 'hu', Make it correspond to two values
print(message)
Look at the results :
File "<ipython-input-4-39b28704af5a>", line 1
message = {
'name':'jake','hu','age':19,'love':'kongfu'}# Key in name Followed by 'hu', Make it correspond to two values
^
SyntaxError: invalid syntax
SyntaxError: invalid syntax Grammar mistakes , Is a compilation error ,python When the compiler is processing , The syntax is found to be irregular , Issue compilation error . therefore , So it looks like , Keys and values are one-to-one correspondence , There can only be one value after the key , But this value can be a string , It could be a number , So can it be a list , What about tuples ?
Practice is the only criterion for testing truth , Don't talk much , Code up :
message = {
'name':['jake','hu'],'age':19,'love':'kongfu'}# Use a list after the key to store values , In this way, multiple... Can be stored in the list ’ value ‘
print(message)
{
'name': ['jake', 'hu'], 'age': 19, 'love': 'kongfu'}
If you put tuples in the position of values , It will also report a mistake , The specific reasons are not explained here .
Get the elements in the dictionary
All the elements in the dictionary are accessed by key names , When we want to get a certain value , Just point out the corresponding key name , You can get the corresponding value . for example :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message['name'])
print(message['age'])
jake
19
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message.get('name'))
print(message.get('age'))
print(message.get('favorite'))# Be careful :get Method if no corresponding value is found , Will be output None, It can also be followed by a default value .
jake
19
None
Addition and modification of elements in the dictionary
In the dictionary , Want to add key value pairs , Directly add , Just define the key and value in this dictionary . for example :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
message['height'] = 182
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
{
'name': 'jake', 'age': 19, 'love': 'kongfu', 'height': 182}
Modifying the value in the dictionary also directly indicates the key name , Then assign the new value to the key name . for example :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
message['age'] = 21
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
{
'name': 'jake', 'age': 21, 'love': 'kongfu'}
The deletion of elements in the dictionary
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
del message['age']
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
{
'name': 'jake', 'love': 'kongfu'}
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
num = message.pop('age')# eject , And delete the value of the specified key
print(num)
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
19
{
'name': 'jake', 'love': 'kongfu'}
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
num = message.popitem()# Pop up a key value tuple randomly
print(num)
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
('love', 'kongfu')
{
'name': 'jake', 'age': 19}
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
message.clear()
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
{
}
Python The characteristics of a dictionary
Some common operations in dictionaries
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message.keys())# Return a dictionary containing all key A list of
print(message.values())# Return a dictionary containing all value A list of
# set default , If the bond exists , Return value , If the key doesn't exist , Create key , The value is defaults to None, Values can also be customized setdefault(key,default=None)
print(message.setdefault('play'))
# Update the specified key content in dictionary format , If it does not exist , Create keys and values
print(message.update({
'play':'pingpang'}))
print(message)
print(message.items())# Return the key value of the dictionary in tuple form
# Measurement Dictionary , The number of key-value pairs
print(message)
print(len(message))# Measurement Dictionary , The number of key-value pairs
dict_keys(['name', 'age', 'love'])
dict_values(['jake', 19, 'kongfu'])
None
None
{
'name': 'jake', 'age': 19, 'love': 'kongfu', 'play': 'pingpang'}
dict_items([('name', 'jake'), ('age', 19), ('love', 'kongfu'), ('play', 'pingpang')])
{
'name': 'jake', 'age': 19, 'love': 'kongfu', 'play': 'pingpang'}
4
How to determine whether a value is in the dictionary ? as follows :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
```python
# Determine whether the specified key is in the dictionary , stay , return True, otherwise , return False
'name' in message
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
True
Traversal of dictionaries adopt for … in …: The grammatical structure of , We can iterate through strings 、 list 、 Tuples 、 Dictionary and other data structures . for example :
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
for i in message:# Traversal keys
print(i)
for j in message.values():# Traversal value
print(j)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
name
age
love
jake
19
kongfu
Definition of set : A collection is a kind of Disorder does not repeat Element collection for , Collection is similar to the previous element list , Can store multiple data , But these data are not repeated .
You can use braces { } perhaps set() Function to create a collection , Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary .
Collection objects also support intersections (intersection), Difference set (difference)、 Union and symmetric difference (sysmmetric_difference)
s1 = {
1,2,3,4,5,5}# Create a collection
print(s1)# By printing, we can see that there are no same elements in the set
s2 = set('34567')# adopt set() Function to create a collection , disorder
s3 = set('1234')
print(s2)
print(s3)
# Collections also support intersections , Difference set , Union and symmetric difference
print(s2&s3)# intersection :& The common part of two sets
print(s2|s3)# Combine :| Two sets merge , There are no repeating elements
print(s2-s3)# Difference set :- Only the elements of the preceding item , There is no element in the following item .
print(s2^s3)# Symmetric difference set (^): There is only a perhaps b in , But not in both
type(s1)# View data type
{
1, 2, 3, 4, 5}
{
'6', '7', '5', '4', '3'}
{
'4', '1', '3', '2'}
{
'4', '3'}
{
'6', '1', '7', '2', '5', '4', '3'}
{
'5', '6', '7'}
{
'6', '7', '2', '5', '1'}
set
Adding and deleting a collection
s1 = {
1,2,3,4,5}
print(s1)
# add(), Add elements to the collection irregularly
s1.add('jk')
print(s1)
# update() You can also add elements , And the parameters can be of different types , And separated by commas
s1.update('8','9',[6,7])# You can't just add int type , Otherwise, the report will be wrong
print(s1)
#remove(), Delete the specified element in the collection , An error will be reported when the specified element does not exist
s1.remove(1)
print(s1)
#discard(), Is to delete the specified element in the collection , And if the element doesn't exist , No mistake.
s1.discard('jk')
s1.discard('aj')
print(s1)
#pop(), No logical delete elements
s1.pop()
print(s1)
{
1, 2, 3, 4, 5}
{
1, 2, 3, 4, 5, 'jk'}
{
1, 2, 3, 4, 5, 'jk', '8', 6, 7, '9'}
{
2, 3, 4, 5, 'jk', '8', 6, 7, '9'}
{
2, 3, 4, 5, '8', 6, 7, '9'}
{
3, 4, 5, '8', 6, 7, '9'}
These are some basic daily operations about sets and dictionaries .