Learning programming is easy and rough. Most of the time, the more you learn, the faster you forget. But programming always has an Epiphany, and the moment of Epiphany is currently based on you and eraser stick to punch for 100 days, in the comments section of eraser stick to learn from eraser, after 100 days, eraser will send out a mysterious prize.

Completed articles

The title link
1. This is the right way to start learning Python Juejin. Cn/post / 691636…
2. Learn data types and input and output functions without barriers, and snowball into Python Juejin. Cn/post / 691668…
3. No programming without twists, learn Python by snowballing Juejin. Cn/post / 691711…
4. Learn Python halfway through the list Juejin. Cn/post / 691744…
5. The nature of Python loops is that a piece of code is too lazy to repeat itself Juejin. Cn/post / 691786…
6. Python tuples, immutable lists, snowball learning Python Juejin. Cn/post / 691816…

This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser

How to use Python dictionary

In this blog post, we are going to learn about dictionaries. Dictionaries are non-sequential data structures that cannot be indexed.

7.1 Basic Operations of dictionaries

7.1.1 Dictionary definitions

Dictionary may be regarded as a kind of list data structure, data and can accommodate a lot of other types of containers, but elements of dictionary use “key-value to said,” and “key-value pairs, the relation of the key and the value can be described as, through the key value (this is the core concept in the dictionary, like through radical dictionary).

The syntax format of the dictionary is as follows:

# my_dict is a variable nameMy_dict = {key1Value:1, the key2Value:2.. }Copy the code

The dictionary value, namely, value 1 and value 2 in the above format, can be a numeric value, string, list, tuple, 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))
Copy the code

The output is:

{'red': 'red'.'green': 'green'.'blue': 'blue'}
<class 'dict'>
Copy the code

Now we need to re-establish the knowledge of dictionaries, which are key to value one-to-one correspondence.

7.1.2 Obtaining the Dictionary Value

Dictionaries are defined by keys, and values are retrieved by keys, so no duplicate keys are allowed in dictionaries. The syntax for getting a value from a dictionary is:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
print(my_dict["red"])
Copy the code

Look closely at the retrieval of elements in a list, except that the index position is replaced by a key.

7.1.3 Add, modify, and delete elements in the dictionary

Add elements

Adding an element to a dictionary is as simple as using the following syntax.

My_dict [key] = valueCopy the code

For example, add an orange key to the color translation dictionary as follows:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
my_dict["orange"] = "Orange"

print(my_dict)
Copy the code

If you want to add more key-value mappings to the dictionary, you can write them one by one.

Modify the element

Changing an element in the dictionary remember that it is more accurate to change the value of an element, such as changing the value red corresponding to red in the code to a light red.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
my_dict["red"] = "Light red"

print(my_dict)
Copy the code

The job is done by making changes with my_dict[key to change] = the new value.

Remove elements

If you want to delete a specific element in the dictionary, you simply use the del keyword plus my_dict[the key of the element to be deleted].

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
del my_dict["red"]

print(my_dict)
Copy the code

The above can remove specific elements, using one of the dictionary’s clear methods to clear the dictionary.

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

print(my_dict)
Copy the code

This will output {}, which represents an empty dictionary.

In addition to emptying the dictionary, you can also delete dictionary variables directly.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
del my_dict

print(my_dict)
Copy the code

After deleting the dictionary variables, my_dict program directly reported an error, indicating that name ‘my_dict’ is not defined variables, when deleting the dictionary must be careful not to delete the entire dictionary by mistake, unless the program requires such implementation.

7.1.4 Supplementary knowledge of dictionaries

An empty dictionary

The syntax for creating an empty dictionary is as follows:

my_dict = {}
Copy the code

Empty dictionaries are usually used for logical placeholder, which is a tricky trick to declare first and then expand.

Gets the number of dictionary elements

Len can be used to get the number of elements in both lists and tuples. The same method applies to dictionaries, and the syntax is as follows:

my_dict_length = len(my_dict)
Copy the code

The empty dictionary has zero elements, so you can try it out.

Dictionary readability writing

In many cases, a program can not be independently completed by one person, but requires the cooperation of a team. How to make your code readable (others can understand) becomes very important when writing the code. Dictionaries recommend defining one element in a row for readability.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}

print(my_dict)
Copy the code

7.2 Dictionary Traversal

The dictionary also iterates through every element in the output, and for the dictionary we already know that it’s made up of key-value pairs, so the corresponding iterating output has all the keys, all the keys, all the values.

7.2.1 Traversing the Key-value of the dictionary

To get all the keys of a dictionary, call the items method of the dictionary, for example:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}

print(my_dict.items())
Copy the code

Enter the content as:

dict_items([('red'.'red'), ('green'.'green'), ('blue'.'blue')])
Copy the code

Next loop output dictionary content, there are several different ways to write, first try to write the following code, in the knowledge point learning.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}

My_dict is traversed directly
for item in my_dict:
    print(item)

Walk through the items method of my_dict
for item in my_dict.items():
    print(item)

The items method of my_dict is iterated over and received with key and value
for key,value in my_dict.items():
    print(Key :{}, value :{}".format(key,value))
Copy the code

Please refer to the above three output contents by yourself.

  1. The first one prints all the keys;
  2. The second prints each key-value pair as a tuple;
  3. The third type prints the key and value directly by assigning values between variables and tuples.

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

a,b = (1.2)
print(a)
print(b)
Copy the code

Note that when assigning variables in this way, make sure that the variables on the left correspond to the elements in the tuple on the right. One variable corresponds to one item in the tuple in the same order. ValueError: Too many values to unpack.

7.2.2 Traversing the keys of the dictionary

You can get all the keys of a dictionary directly by using the keys method, as shown in the following code:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}


for key in my_dict.keys():
    print(key)
Copy the code

7.2.3 Traversing dictionary values

There is the keys method to get the keys, which corresponds to getting all the values through values. Because this place is too similar to the above content, if you want to become a qualified programmer, the daily amount of code learning can not be reduced, so I leave this part to you.

7.3 Combination of dictionaries with other data types

The first step is to realize that a dictionary is a container that can contain any data type. Dictionaries are also a data type that can be contained by container classes such as lists and dictionaries themselves. It’s very convoluted, isn’t it? The core of it is very simple, as you will understand after looking at the code.

7.3.1 List nested Dictionaries

To see the effect directly, a list can be nested with dictionaries.

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

7.3.2 Dictionary nested list

The values of elements in a dictionary can be lists, as follows:

my_dict = {"colors": ["Red"."Green"]."nums": [1.2.3.4.5]."name": [eraser]}
print(my_dict)
Copy the code

7.3.3 Dictionary Nested Dictionaries

Dictionary values can be of any data type, which of course can be dictionaries, 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)
Copy the code

The above content is very simple writing method, sum up a word is a doll.

7.4 Dictionary method

Dictionaries have special methods that need to be explained separately. If you want to see all of the dictionary’s methods, use the dir built-in function call.

7.4.1 fromkeys method

The purpose of this method is to create a dictionary with the following syntax:

# Notice that this method is called directly through dict
# seq is a sequence that can be a tuple or a dictionary
my_dict = dict.fromkeys(seq)
Copy the code

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

my_list = ['red'.'green']

my_dict = dict.fromkeys(my_list)
{'red': None, 'green': None}
print(my_dict)

my_dict1 = dict.fromkeys(my_list, "Dictionary values")
print(my_dict1)
Copy the code

The first way is to find that all values in the output dictionary are None (Python’s special value, equivalent to null). This is because the dictionary default is not set. The default is None. If you need to initialize this value when defining the dictionary, assign the value to the second argument in the method.

7.4.2 the get method

The get method is used to get a value by key, and can be set to return a default value if none exists, as in the following code:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
print(my_dict.get("red"))  # return red
print(my_dict.get("red1")) # returns None

print(my_dict.get("red1"."Set a default that could not be found to return."))
Copy the code

7.4.3 setdefault method

The setdefault method is basically the same as the get method. The difference is that if setdefault cannot find the specified key, it will automatically insert the key value into the dictionary. For example:

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}
print(my_dict.setdefault("red")) # return red
print(my_dict.setdefault("orange")) # returns None
print(my_dict) Output # {' red ':' red ', 'green' : 'green' and 'blue' : 'blue', 'orange' : None}
Copy the code

The last line of code output already contains the key orange and the value None. You can test the default values using dict.setdefault(“orange”,” orange”).

7.4.4 pop method

This method is used to delete dictionary elements in the following syntax:

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

Dict.pop (key[,default]) where key is a required parameter and [] contains non-required parameters, so you can understand what the syntax is.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}

# delete the specified item
ret_value = my_dict.pop('red')
# output deleted red
print(ret_value)
{'green': 'green', 'blue': 'blue'}
print(my_dict )
Copy the code

When using the pop method, if the key is found, the key-value pair is removed. If the key is not found, defalut returns the value set. If the value is not set, an error is reported.

my_dict = {"red": "Red"."green": "Green"."blue": "Blue"}

# delete the specified item. If no value is found, an error is reported
ret_value = my_dict.pop('red2')

Key1 returns the value set later
ret_value = my_dict.pop('red1'."Returned value not found")
Copy the code

7.5 Summary of this blog

Dictionaries, like lists and tuples, are very important data types in Python. Dictionaries are used more often because of the concept of key-value pairs.

The last bowl of chicken soup

I naively thought that money is omnipotent, and then I found that money is not omnipotent, is omnipotent. O ha ha ~ O (studying studying)

🌸 🌸 🌸 🌸 🌸 🌸 🌸 🌸


Today is day 6/100 of continuous writing. If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.