Dictionaries dictionaries dict for advanced python tutorials

  • 2020-04-02 14:03:21
  • OfStack

The basic tutorial introduces basic concepts, especially objects and classes.

The advanced tutorial expands on the basic tutorial to explain the details of Python. Hopefully, after the advanced tutorial, you'll have a fuller understanding of Python.

As we said before, a list is a class in Python. A particular table, such as nl = [1,3,8], is an object of this class. We can call some methods on this object, such as nl.append(15).

We're going to introduce a new class, dictionaries. Like lists, dictionaries can store multiple elements. This object that stores multiple elements is called a container.

The basic concept

Common ways to create a dictionary:


>>>dic = {'tom':11, 'sam':57,'lily':100}
>>>print type(dic)

A dictionary is similar to a table in that it contains multiple elements, each separated by a comma. But the elements of a dictionary contain two parts, keys and values. Keys are usually represented as strings, and keys can be represented as Numbers or truth values (immutable objects can be used as keys). The value can be any object. Keys and values correspond to each other.

In the example above, 'Tom' corresponds to 11, 'Sam' to 57, and 'lily' to 100
 
Unlike tables, the elements of a dictionary have no order. You cannot refer to elements by subscripts. Dictionaries are referenced by keys.


>>>print dic['tom']
>>>dic['tom'] = 30
>>>print dic

Build a new empty dictionary:


>>>dic = {}
>>>print dic

 

A way to add a new element to a dictionary:


>>>dic['lilei'] = 99
>>>print dic

Here, we refer to a new key and assign it a corresponding value.

A circular call to a dictionary element


dic = {'lilei': 90, 'lily': 100, 'sam': 57, 'tom': 90}
for key in dic:
    print dic[key]

In the loop, each key of dict is extracted and assigned to the key variable.

From the print result, we can confirm again that the elements in dic are in no order.

Common methods of dictionaries


>>>print dic.keys()           # return dic All the keys
>>>print dic.values()         # return dic All of the values
>>>print dic.items()          # return dic All elements (key value pairs)
>>>dic.clear()                # empty dic . dict into {}

 

There is another very common usage:


>>>del dic['tom']             # delete dic ' tom' The element

Del is a reserved keyword in Python for deleting objects.

Similar to the table, you can use len() to look up the total number of elements in the dictionary.


>>>print(len(dic))

conclusion

Each element of the dictionary is a key-value pair. The elements have no order.


dic = {'tom':11, 'sam':57,'lily':100}
dic['tom'] = 99
for key in dic: ...
del, len()


Related articles: