Python BASICS (7): dictionaries and collections, and python dictionaries

Source: Internet
Author: User
Tags hashable

Python BASICS (7): dictionaries and collections, and python dictionaries

I. Dictionary

A dictionary is a set of data similar to a list. What are its characteristics?

Feature 1: The dictionary has a key and a value. The key must be unique and retained. That is, the key must be hashed. There is no requirement for the value.

Feature 2: The dictionary is unordered.

1. Definition of the dictionary:

The dictionary is defined by "{}" and the key and value form "key: Value" in it. Each key-value pair is separated. Example:

dict = {"name":"Leo""age":24, "hobby":["football","basketball"]}

We can see that the value of the dictionary can be of any data type.

2. dictionary access

Some students may wonder why a dictionary should be designed when the list is available? This involves the problem of changing the space for time. The dictionary search speed is much faster than the list, and it will not slow down as the dictionary key increases. Obviously, the list will not work, when the list element is added, its search speed slows down, but the same data dictionary must be stored more space than the list, because the dictionary is composed of key-value pairs. Then we will continue to discuss the dictionary access. The list can be accessed through the index. Obviously, the dictionary does not have a location index, but it is composed of key-value pairs. It has a key, you can use a unique key to quickly access the corresponding value. For example:

dict = {"name":"Leo""age":24, "hobby":["football","basketball"]}

Print the result: "Leo ".

What should I do if I want to add new content to the dictionary above? Add a key-value pair, for example:

dict["alias"] = "erge"


In this case, the key "alias" in the dictionary "dict" is assigned a value of "erge ".

Printed results: "{'name': 'Leo ', 'age': 24, 'hoby': ['football', 'bucketball'], 'Alias ': 'erge '}"

What if I want to modify a value in the dictionary above? Or through key-value pairs. For example, to modify the value of "name", the example is as follows:

dict["name"] = "Tom"

In this case, the key "name" in dict is actually assigned a value of "Tom ".

Print result: {'name': 'Tom ', 'age': 24, 'hoby': ['football', 'bucketball'], 'Alias': 'erge '}

In fact, we can see from the above that the keys in the dictionary are unique. When we repeat the keys again, the values in the original keys will be replaced by new ones, and they will always be unique.

3. dictionary-related methods

A. get () method: get the value.

dict = {"name":"Leo""age":24}

Print the result: "Leo ". If the key of the input parameter in the get () method does not exist in the dictionary, a None is returned. In actual development, it is also possible to return a specific value if it does not exist. The usage is as follows:

dict = {"name":"Leo""age":24}

Print the result: "Tom ". When the second parameter in get () indicates that it does not exist, a specific value is returned. If it exists, the corresponding value in the dictionary is returned.

B. setdefault () method: The usage is similar to get (), but when the key does not exist, a key is set for it and a default value is added.

dict = {"name":"Leo""age":24}

Printed results: "{'name': 'Leo ', 'age': 24, 'abc': 'Tom'}", setdefault () the second parameter is the default value to be set. If this parameter is left blank, the default value is None. Try it by yourself. If the key exists in the dictionary, the corresponding value is still returned in the dictionary.

C. copy () method: copy. Here the copy is still shortest copy (Shortest copy)

dict = {"name":"Leo""age":24}
dict2 = dict.copy()

Printed result: "{'name': 'Leo ', 'age': 24 }".

D. update () method:

dict = {"name":"Leo""age":24}
dict2 = {"alias":"erge","sex":"F"}

Printed result: "{'name': 'Leo ', 'age': 24, 'Alias': 'erge', 'sex': 'F '}". What will happen if the keys in dict2 overlap with those in dict? Try it by yourself. (Note: As mentioned above, there are duplicate keys, and the old ones will be replaced by new ones)

E. clear () method: delete all elements in the dictionary.

dict = {"name":"Leo""age":24}

Printed result: "{}". Print an empty dictionary. We need to differentiate del. This is also the deletion of an object. This is complete, and del will delete all references to an object (and the memory will be recycled later ), it can be understood that the object is deleted from the memory. While clear () only deletes the elements in it, and the dict object still exists.

F. pop () method: Delete the value corresponding to the key and return the deleted value. If no value exists, the default value is returned.

dict = {"name":"Leo""age":24}

Print result:

The second parameter in pop () is the default value. If the key does not exist, the default value is returned. If you want to pop a key that does not exist, what will happen.

G. popitem () method: deletes a random key-value pair.

dict = {"name":"Leo""age":24}

The printed results are not given, because they are randomly deleted and the results are uncertain. You can try it. However, key-value pairs at the end of the dictionary are usually deleted. Note that, this method cannot be used for empty dictionaries.

H. fromkeys () method to create a new dictionary

seq = ('name''age''sex')
dict ={}
new_dict = dict.fromkeys(seq,10)

Printed result: "{'name': 10, 'age': 10, 'sex': 10 }". The first parameter list in fromkeys () is used as the key to generate a new dictionary, and the second parameter is the value of the new dictionary. If this parameter is not written, the default value is None. The dictionary generated using this method has different keys but the values are the same. For creating a dictionary, there is also a dict () method in the built-in function. The usage is as follows:

a = dict(name="Leo",age=20)

Printed result: "{'name': 'Leo ', 'age': 20 }". In addition to the keyword format, there are also the following forms:

a = [('name''Leo'), ('age', 20)]
new_dict = dict(a)

Print result: {'name': 'Leo ', 'age': 20}. You can understand the result by iterative object method. In fact, there is another method for ing functions. Since the built-in method zip () has not been introduced, I will not give an example here. If you are interested, please study it first.

I. _ contains _ () method. If the key is in the dictionary, True is returned. Otherwise, False is returned.

dict = {"name":"Leo""age":24}

Print the result: "True ".

J. keys ()/values ()/items () Get the key/value/key-value pair in the dictionary

dict = {"name":"Leo""age":24}

Print result:

Their return values are some unknown data types (in fact, they return an iterator object and end later). You can use list () to change the result to a list and rewrite print:

dict = {"name":"Leo""age":24}

Print result:


4. Hash

As mentioned above, keys in the dictionary must be hashable. What is a hash? It is the literal translation of English Hash. What about Hash. The hash algorithm must be mentioned: the hash algorithm maps binary values of any length to short binary values of a fixed length. From this introduction, we can see that hash is an algorithm that can improve efficiency, why? For example, there are 1 million articles, and I will give you an article from it to confirm whether it is one of these articles? Every article compares words one by one, and it is terrible to think about it. By using the hash algorithm, each article can be converted into a fixed-length number, you only need to compare the number of the article with the number of the 1 W article, whether the efficiency is much higher. This is why keys in the dictionary can be hashed, which greatly improves the dictionary search efficiency. How can we determine whether a parameter can be hashed () if it can be even hashed, a hash value will be returned; otherwise, an error will be reported. Example:

l = 'abc'

Printed result: "1998840242 ". For students with poor foundations, you can learn more about hash on the Internet.

Ii. Set

A set can be seen as a dictionary without values. It has the following features:

Feature 1: Like a dictionary,

Feature 2: the elements in the set are unique, that is, the elements in the set cannot be repeated. (Of course, the elements in it are also hashable)

1. Create a set

s = {1,2,3}
print(s, type(s))

Print the result: "{1, 2, 3} <class 'set'>", print the set s, and check whether its type is set.

In addition to the preceding method, you can also use the built-in function set () to create a set.

s = [1,2,3]

Print result: {1, 2, 3 }.

There is also a frozenset () function in the built-in function, which creates an immutable set. That is to say, a set can be divided into variable set sets and immutable frozenset sets.

2. set related methods

A. add () method: add an element

s = {1,2,3}

Print result: {1, 2, 3, 6 }. You can try to add an existing element to the set to see if it can be successfully added.

B. remove () method: delete an element

s = {1,2,3}

Print result: {1, 3 }.

C. pop () method: Randomly delete an element.

s = {1,2,3}

Print result: 1 {2, 3 }. The pop method returns the deleted element.

D. discard () method: delete an element

s = {1,2,3}

Print result: {1, 3 }. At this time, dicard () and remove () are used in the same way. The difference between them is that when you delete a nonexistent element, remove () will report an error, while discard () no. You can try it yourself.

E. update () method: extends the set.

s1 = {1,2,3}
s2 = {4,5,6}

Print result: {1, 2, 3, 4, 5, 6 }. The parameters in Update () are not necessarily set, but also list, tuples, and dictionaries, as long as they are objects that can be iterated.

3. Set Operations

The set operation here does not change the original set. Except for the operators "|", "&", "-", and "^, you can also use some methods.

A. Union set1 | set2

s1 = {1,2,3}
s2 = {4,5,6}
s = s1.union(s2)

Print result: {1, 2, 3, 4, 5, 6 }. The union () method is used to implement the union.

B. Intersection set1 & set2

s1 = {1,2,3,4}
s2 = {3,4,5,6}
s = s1.intersection(s2)

Print result: {3, 4 }. Use the intersection () method to achieve intersection.

C. Differential set set1-set2

s1 = {1,2,3,4}
s2 = {3,4,5,6}
s = s1.difference(s2)

Print result: {1, 2 }. Use the difference () method to implement the difference set. You can try s2.difference (s1.

D. Symmetric Difference set1 ^ set2

s1 = {1,2,3,4}
s2 = {3,4,5,6}
s = s1.symmetric_difference(s2)

Print result: {1, 2, 5, 6 }. Use the effecric_difference () method to implement the difference set.

E. Determine the subset

s1 = {1,2,3,4}
s2 = {3,4}
s = s1.issuperset(s2)

Print the result: True. That is to say, s2 is a subset of s1. In addition to the issuperset () method, you can try the issubset () method to determine the subset.

Iii. iterator

As mentioned previously, What Is iteration? The list we have learned can all be iterated. You can use for loop traversal to iterate objects. An object that can be iterated is a general term and is not a definite object or type. Each object that can be iterated has an iterator.

What is the iterator? It is a stateful object that can return the next value in the container when you call the next () method, any object that implements the next () method in _ iter _ and _ next _ () (python2) is an iterator __iter _ returning the iterator itself, __next _ return the next value in the container. If there are no more elements in the container, the StopIteration exception is thrown. It is not important to know how they are implemented. Therefore, the iterator is an object that implements the factory mode. It returns the value every time you ask for the next value. When you call the next () method each time, you need to do two things: modify the status of the next call to the next () method, and generate a returned result for the current call. The iterator is like a lazy loading factory. It is generated and returned only when someone needs it. When it is not called, it is in sleep state and waits for the next call. For more information, see

The iter () method can be used to obtain the iterator that can iterate objects. Example:

l = [1,2,3,4]
a = iter(l)

Print the result: <class 'list _ iterator'>. Since the iterator is an object, we can define the iterator by ourselves. More information will be provided later.



Benefits:ReplyPython booksTo obtain some well-recognized e-books learned by python.


Tips:The Code involved above. Beginners must think carefully and think carefully about it. I have also provided all the running results in the article. Do not look down. For beginners, the results achieved by themselves are often different from those imagined.


Note:The author's content is original and reprinted to indicate the source. Due to my limited ability, please contact the author for any errors or omissions. Thank you!

If you have any questions about installing or using python, you can join the QQ group: 476581018.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.