Do you remember learning the Python dictionary with the old ones?

  • 2020-04-02 14:09:14
  • OfStack

Dictionary, do you still use this? With the development of the Internet, fewer and fewer people use it. Many people are used to searching on the Internet, not only the web version, but also the mobile version of various dictionaries. I used to use a small xinhua dictionary.

Xinhua dictionary is the first modern Chinese dictionary in China. The earliest name was the wuji small dictionary, but it was never completed. Since 1953, began to recompile, its ordinary example entirely USES "the wu ji small dictionary". It began to be published in 1953 and was revised repeatedly, but the first edition was xinhua dictionary published by the commercial press in 1957. Originally compiled by the new Chinese dictionary society, it was merged into the dictionary editing office of the institute of linguistics of the Chinese academy of social sciences (now the institute of linguistics of the Chinese academy of social sciences) in 1956. Xinhua dictionary is published by the commercial press. After several generations of hundreds of experts and scholars more than 10 large-scale revisions, reprint more than 200 times. It has become by far the highest circulation dictionary in the world publishing history.
Dictionaries are not here to catch up. But remind the reader to think about how we use the dictionary: first look up the index (whether it is pinyin or look up the word), and then find the corresponding content through the index.

This method can quickly find the target.

In python, there is a similar data, not only similar, the name of this data is called dictionary, translated as a dictionary, similar to the previous int/ STR /list, this type of data name is :dict

Depending on management, know how to set up the dict and its associated attribute methods.

Because you already have the basics, you can learn this quickly.

Previously, I suggested that readers should learn a good method of inquiry. For example, if they want to know about STR's attribute method, they can use it in interactive mode:


>>>help(str)

Will get all the relevant content.

Now switch to dir and you'll get the same result. It's just easier. In interactive mode:


>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']


Forget those beginning with __ (double underscore). Look at the back. If you want to know more, you can do this:


>>> help(dict.values)

Then came:


Help on method_descriptor: values(...)
    D.values() -> list of D's values
(END)

This is where values, the built-in function, is displayed. Hit the q key on the keyboard to return.

An overview of the

Dict in python has the following characteristics:

Dict is variable
Dict can store any number of Python objects
Dict can store any python data type
Dict stores data in the form of: key:value, or "key:value" pairs, each key being unique.
Dict is also known as an associative array or hash table.
All of the above, if not quite understand, also do not matter, through the following learning, especially through various experiments, will be able to understand.

Create a dict

There are more methods to create dict than int/ STR /list, so why are there more? The general rule is that complex things will have a variety of channels, this is also from the point of view of security and convenience.

Method 1:

Create an empty dict, an empty dict, and you can add something to it later.


>>> mydict = {}
>>> mydict
{}

Create dict with content.


>>> person = {"name":"qiwsir","site":"qiwsir.github.io","language":"python"}
>>> person
{'name': 'qiwsir', 'language': 'python', 'site': 'qiwsir.github.io'}

"Name ":"qiwsir" is a key-value pair. The name in front is called key, and the value in the back is qiwsir. In a dict, the keys are unique and cannot be repeated; Values correspond to keys and can be repeated. The key values are separated by a semicolon (:) in English, and each pair of key values is separated by a comma (,) in English.


>>> person['name2']="qiwsir"    # This is a direction dict The method of adding key-value pairs in
>>> person
{'name2': 'qiwsir', 'name': 'qiwsir', 'language': 'python', 'site': 'qiwsir.github.io'}

The following illustrates the process of adding content from an empty dict:


>>> mydict = {}
>>> mydict
{}
>>> mydict["site"] = "qiwsir.github.io"
>>> mydict[1] = 80
>>> mydict[2] = "python"
>>> mydict["name"] = ["zhangsan","lisi","wangwu"]
>>> mydict
{1: 80, 2: 'python', 'site': 'qiwsir.github.io', 'name': ['zhangsan', 'lisi', 'wangwu']}

>>> mydict[1] = 90 # If so, the value of the key is modified 
>>> mydict
{1: 90, 2: 'python', 'site': 'qiwsir.github.io', 'name': ['zhangsan', 'lisi', 'wangwu']}

Method 2:


>>> name = (["first","Google"],["second","Yahoo"])   # This is another data type, called a tuple, which we'll talk about later 
>>> website = dict(name)
>>> website
{'second': 'Yahoo', 'first': 'Google'}

Method 3:

This method, unlike the previous one, USES the fromkeys


>>> website = {}.fromkeys(("third","forth"),"facebook")
>>> website
{'forth': 'facebook', 'third': 'facebook'}

It should be noted that this approach is to re-establish a dict.

Access the value of dict

Because dict stores data in the form of key-value pairs, as long as you know the key, you can get the value. This is essentially a mapping.


>>> person
{'name2': 'qiwsir', 'name': 'qiwsir', 'language': 'python', 'site': 'qiwsir.github.io'}
>>> person['name']
'qiwsir'
>>> person['language']
'python'
>>> site = person['site']
>>> print site
qiwsir.github.io

As mentioned earlier, keys can increase values in dict, keys can change values in dict, and keys can access values in dict.

You can compare it with the list. If we access the elements in the list, we can index them to (list[I]), or if we want the machine to tour them, we can use the for statement. To review:


>>> person_list = ["qiwsir","Newton","Boolean"]  
>>> for name in person_list:
...   print name
... 
qiwsir
Newton
Boolean

So can dict also be looped around with a for statement? Sure, here are some examples:


>>> person
{'name2': 'qiwsir', 'name': 'qiwsir', 'language': 'python', 'site': 'qiwsir.github.io'}
>>> for key in person:
...   print person[key]
... 
qiwsir
qiwsir
python
qiwsir.github.io

knowledge

What is an associative array? The following explanation is from wikipedia

In computer science, an Associative Array, also known as a Map or Dictionary, is an abstract data structure that contains ordered pairs similar to keys or values. Ordered pairs in an associative array can be repeated (such as multimap in C++) or not (such as map in C++).
This data structure contains the following common operations:

1. Add a pairing to the associative array
2. Remove the pairing from the associative array
3. Modify the pairing in the associative array
4. Look for pairs based on known keys
The problem with dictionaries is to design a data structure that has the property of associative arrays. A common way to solve the dictionary problem is to use hash tables, but in some cases, you can just use an array of addresses, or a binary tree, or some other structure.
Many programming languages have built-in basic data types that provide support for associative arrays. Content-addressable memory implements associative arrays at the hardware level.
What is a hash table? There is a lot of talk about hash tables, but this is just a snapshot of the concept, more of which can be read on wikipedia.

A Hash table (also known as a Hash table) is a data structure that is accessed directly in an in-memory storage location based on Key value. That is, it accesses the record by mapping the key values to a location in the table through the calculation of a function, which speeds up the lookup. This mapping function is called the hash function, and the array of records is called the hash table.


Related articles: