程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python -- basic use of dictionaries and collections

編輯:Python

Dictionaries

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

  1. Using key names

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
  1. get Method
    for example : adopt get() Function to find the value in the dictionary
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

  1. Deleting a key value pair from a dictionary , Yes, it is del Directly delete
message = {
'name':'jake','age':19,'love':'kongfu'}
print(message)
del message['age']
print(message)
{
'name': 'jake', 'age': 19, 'love': 'kongfu'}
{
'name': 'jake', 'love': 'kongfu'}
  1. pop(), eject , Returns and deletes the value corresponding to the specified key
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'}
  1. Pop up a key value tuple randomly ( The reason for randomness is that dictionaries are out of order )
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}
  1. clear Empty dictionary
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

  1. The dictionary is out of order , So the dictionary has no index value ;
  2. The dictionary has no index value , So the dictionary takes values by keys ,( The key of a dictionary is equivalent to the index of a list );
  3. Dictionary takes value by key , So the key of the dictionary is unique and cannot be modified ;
  4. The key of the dictionary cannot be modified , Therefore, variable types of data such as lists and dictionaries cannot be used as keys for dictionaries .

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

aggregate

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved