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

Python dictionary has been mastered [source code attached]

編輯:Python

Look it up in a dictionary ,Python How to use a dictionary

I've learned lists and tuples , Then these two are arranged in order , So you can use the index to get the value , What this blog is going to learn is a dictionary , As can be seen from the above , The dictionary definitely can't get the value according to the index , It's just that there's no order , Non sequential data structures .

Basic operation of dictionary

Dictionary definition

A dictionary can be seen as a tabular data structure , It is also a container that can hold many other data types , But the elements in the dictionary use “ key - value ” To represent the , and “ key - value ” Pairs appear , The relationship between a key and a value can be described as , Take the value of ( This is the core concept of a dictionary , It's like looking up a dictionary through radicals ).

The grammar of the dictionary is as follows :

# my_dict It's a variable name
my_dict = { key 1: value 1, key 2: value 2......}

Where the dictionary value is the value 1 value 2 It can be a number 、 character string 、 list 、 Tuples, etc .

For example, a Chinese English table can be represented by a dictionary .

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
print(my_dict)
print(type(my_dict))

The output is :

{'red': ' Red ', 'green': ' green ', 'blue': ' Blue '}
<class 'dict'>

Now it's time to build a new understanding of the dictionary , A dictionary is a one-to-one correspondence between a key and a value .

Get the value of the dictionary

Dictionaries are defined by key values , Get the value through the key , Therefore, duplicate keys are not allowed in the dictionary . The syntax format for getting values in the dictionary is :

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
print(my_dict["red"])

Look at it very much like getting the elements in a list , Just replace the index position with key .

Add elements to the dictionary 、 Modifying elements 、 Remove elements

Add elements

It's very easy to add an element to the dictionary , Only through the following syntax format to achieve .

my_dict[ key ] = value 

For example, in the color translation dictionary just now, add an orange corresponding key value , The code is as follows :

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
my_dict["orange"] = " Orange "
print(my_dict)

If you want to add more key value correspondence in the dictionary , You can write it in turn .

Modifying elements

Modify the elements in the dictionary. Remember that the exact value should be called modifying the value of the element , For example, put the code red Corresponding value Red It is amended as follows Light red , This is done with the following code .

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
my_dict["red"] = " Light red "
print(my_dict)

adopt my_dict[ The key to change ] = New value To modify to complete the task .

Remove elements

If you want to delete a specific element in the dictionary , Just go through del Keywords plus my_dict[ The key of the element to be deleted ] Can finish .

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
del my_dict["red"]
print(my_dict)

The above can delete specific elements , One that uses a dictionary clear Method , You can empty the dictionary .

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
my_dict.clear()
print(my_dict)

The above content will be output {} The symbol indicates an empty dictionary .

Besides clearing the dictionary , You can also delete dictionary variables directly .

my_dict = {"red": " Red ", "green": " green ", "blue": " Blue "}
del my_dict
print(my_dict)

After deleting the dictionary variable , In print my_dict The program directly reports an error , Tips name 'my_dict' is not defined Variable not defined , When deleting a dictionary, be sure not to delete the whole dictionary by mistake , Unless the program requires that .

Supplementary knowledge of dictionaries

An empty dictionary

Just now I have mentioned how an empty dictionary is created , The syntax for creating an empty dictionary is as follows :

my_dict = {}

Empty dictionaries are generally used for logical occupancy , It's so complicated. What is logical occupation , It's a little trick to declare the extension later .

Get the number of dictionary elements

You can use both lists and tuples len To get the number of elements , The same method applies to dictionaries , The syntax is as follows :

my_dict_length = len(my_dict)

The number of elements in an empty dictionary is 0, Try it out .

Dictionary readability writing

Most of the time, a program can't be done by one person alone , Need a team to cooperate , How to make your code readable ( Others can understand ) Height is very important when you write code . Dictionaries are for readability , It is suggested that one line define an element .

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
print(my_dict)

Traversal of dictionaries

The dictionary also needs to traverse every element in the output , As far as dictionaries are concerned, they are composed of key value pairs , The corresponding traversal output has all the key values , All keys , All worth .

Traverse the key of the dictionary - value

Call dictionary items Method can get all the key values of the dictionary , For example, the following code :

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
print(my_dict.items())

The input of the content is :

dict_items([('red', ' Red '), ('green', ' green '), ('blue', ' Blue ')])

Next, loop out the dictionary content , There are several different ways of writing , First try to write the following code , In the process of knowledge learning .

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
# Direct pair my_dict Traversal
for item in my_dict:
print(item)
# Traverse my_dict Of items Method
for item in my_dict.items():
print(item)
# Traverse my_dict Of items Method , And use key And value receive
for key,value in my_dict.items():
print(" key :{}, value :{}".format(key,value))

Please refer to the above three output contents .

  1. The first output is all key ;
  2. The second is to output each key value pair as a tuple ;
  3. The third is to output the key and value directly through the assignment between variables and tuples .

For the assignment between variables and tuples, you can refer to the subordinate code :

a,b = (1,2)
print(a)
print(b)

Note that in this way, the variables on the left must be corresponding to the elements in the tuple on the right , A variable corresponds to an item in a tuple , The order also corresponds to . If not, the following errors will appear ValueError: too many values to unpack .

Traverse the key of the dictionary

What I learned above is to traverse the key values of the dictionary , You can go straight through keys Method to get all the keys of the dictionary , For example, the following code :

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
for key in my_dict.keys():
print(key)

Traversal dictionary value

Yes keys Method to get the key , The corresponding is through values Get all values .

This place is too similar to the above , If you want to be a qualified programmer , At the beginning of learning, the amount of code per day cannot be reduced , So this part is for you .

A combination of dictionaries and other data types

First realize that a dictionary is a container , It can contain any data type . A dictionary is also a data type , It can be included by container classes such as lists and dictionaries themselves .

It's very winding, isn't it , The core is very simple , After reading the code, you can see .

List nested Dictionary

See the effect directly , A list can nest dictionaries .

my_list = [{"name": " Eraser ", "age": 18},
{"name": " Big eraser ", "age": 20}]
print(my_list)
print(my_list[0])

Dictionary nested list

The value of an element in a dictionary can be a list , As follows :

my_dict = {"colors": [" Red "," green "],
"nums": [1,2,3,4,5],
"name": [" Eraser "]}
print(my_dict)

Dictionary nested dictionary

Dictionary values can be of any data type , It can be a dictionary type of course , So you should be able to read the following code .

my_dict = {"colors": {"keys": [" Red ", " green "]},
"nums": [1, 2, 3, 4, 5],
"name": [" Eraser "]}
print(my_dict)

The above is very simple to write , In a word, they are all dolls .

Dictionary method

There are some special ways to use dictionaries , If you want to see all the ways in the dictionary , According to the use of dir Built in function call .

fromkeys Method

The purpose of this method is to create a dictionary , The syntax is as follows :

# Note that the method goes directly through dict call
# seq It's a sequence , It can be tuples , It could be a dictionary
my_dict = dict.fromkeys(seq)

The next step is to actually create a dictionary using this method .

my_list = ['red', 'green']
my_dict = dict.fromkeys(my_list)
# The following output {'red': None, 'green': None}
print(my_dict)
my_dict1 = dict.fromkeys(my_list, " Dictionary value ")
print(my_dict1)

The first way is to find that all the values in the output dictionary are None(Python Special value in , Equivalent to empty ), This content is because there is no dictionary default value set , Default is None, If you need to initialize the value when defining the dictionary , Assign the second parameter in the method .

get Method

get Method is used for Get value by key , If it doesn't exist, it can be set to return a default value , For example, the following code :

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
print(my_dict.get("red")) # Back to red
print(my_dict.get("red1")) # return None
print(my_dict.get("red1"," Set a default value that cannot be returned "))

setdefault Method

setdefault Methods and get The purpose of the method is basically the same , The difference is when setdefault When the specified key is not found , It will insert the key value into the dictionary , For example, the following code :

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
print(my_dict.setdefault("red")) # Back to red
print(my_dict.setdefault("orange")) # return None
print(my_dict) # Output {'red': ' Red ', 'green': ' green ', 'blue': ' Blue ', 'orange': None}

The output of the last line of code already contains the key orange And value None, You can use dict.setdefault("orange"," Orange ") Test the default values .

pop Method

This method is used to delete dictionary elements , The syntax is as follows :

ret_value = dict.pop(key[,default])

Now that the standard format has been written , First of all, I'd like to add the standard of grammatical format , for example dict.pop(key[,default]) in key Indicates a required parameter ,[] The included parameters are not required , In this way, you can understand what the above grammatical format is .

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
# Delete the specified item
ret_value = my_dict.pop('red')
# Output the deleted red
print(ret_value)
# View dictionary {'green': ' green ', 'blue': ' Blue '}
print(my_dict )

In the use of pop If we find key, The key value pair is deleted , If you can't find it key Returns the defalut Set the value of the , If the value is not set , Will report a mistake .

my_dict = {"red": " Red ",
"green": " green ",
"blue": " Blue "}
# Delete the specified item , If there is no setting, the returned value cannot be found , Direct error
ret_value = my_dict.pop('red2')
# Delete the specified item , Can't find key1 Return the value set later
ret_value = my_dict.pop('red1'," Cannot find the returned value ")

The summary of this blog

A dictionary is the same as a list 、 Tuples are the same Python Very important data types in , Dictionaries have more usage scenarios because of the concept of key value pairs , At the beginning of learning, the advice of eraser is to type code well , First set up the right to Python The overall cognition of , Snowballing Python, It's just the first roll .


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