Python: dictionaries, collections

 dictionary  

        The dictionary type is the only mapping type in Python. "Mapping" is a term in mathematics. Simply understood, it refers to the corresponding relationship between elements, that is, through one element, another element can be uniquely found.

        The dictionary does not have an index. It consists of a key and a value. The key is equivalent to the "index" and the value is equivalent to the content of the index. Among them, key can be a number, string or tuple, but cannot be a list, value can be any, and < /span> will be retained. key is unique and cannot be repeated. If it is repeated, only the last one

        The dictionary type in Python is equivalent to the Map object in Java or C++.

        The syntax format of Python dictionary type is as follows:

        dictName = {'key1':'value1','key2':'value2',...,'key' ;:casting}

Common ways to create a dictionary:

1) dict1 = {"Li Bai":"Jingye Si","Su Shi":"Jiang Chengzi","Wang Zhihuan":"Deng Guanque Tower"}               #Correct

     dict1 = {("Li Bai":"Jingye Si"),("Su Shi":"Jiang Chengzi"),("Wang Zhihuan":"Climbing the Stork Tower")} #Error, this method defines a set

2) dict1 = dict((("Li Bai","Jingyesi"),("Su Shi","Jiang Chengzi"),("Wang Zhihuan","Deng Guanque Tower "))) #Correct, tuple converted to dictionary

     dict1 = dict([("Li Bai","Jingyesi"),("Su Shi","Jiang Chengzi"),("Wang Zhihuan","Climbing the Stork Tower" )]) #Correct List converted to dictionary

3) dict1 = dict(Li Bai = "Jingyesi", Su Shi = "Jiang Chengzi", Wang Zhihuan = "Deng Guanque Tower") #Correct

     dict1 = dict("Li Bai" = "Jingyesi","Su Shi" = "Jiang Chengzi","Wang Zhihuan" = "Deng Guanque Tower") #Error

4) list1 = ["Li Bai", "Su Shi", "Wang Zhihuan"]

      List2 = ["Jingye Si", "Jiang Chengzi", "Deng Guanque Tower"]

      dict1 = dict(zip(list1, list2))                                                                                                                                                                

      print(dict1)

Print result: {'Li Bai': 'Jingyesi', 'Su Shi': 'Jiang Chengzi', ' Wang Zhihuan': 'Climb the Stork Tower'}

4)dict1 = {}

      dict1["Li Bai"] = "Jingyesi"

      dict1["Su Shi"] = "Jiang Chengzi" #This method is often used to modify the key value (or add a dictionary element). If the key does not exist, the key and corresponding value will be added (lists and tuples do not The index assignment will report an error, prompting that the index exceeds)

5)dict1 = {}

     dict1.fromkeys(("Li Bai","Su Shi","Wang Zhihuan"),"Ancients")

      Output: {'Li Bai': 'Ancients', 'Su Shi': 'Ancients', 'Wang Zhihuan 39;: 'Ancients'}    #After assigning a value in this method, dict1 is still empty

Commonly used dictionary functions:

1) keys() function

dictName.keys() #Can output all keys in the dictionary (key)

>>> dict1.keys()
dict_keys(['Li Bai', 'Su Shi', 39;Wang Zhihuan'])

2) values() function

dictName.values() #Can output all key values ​​​​(value) in the dictionary

>>> dict1.values()
dict_values(['Jingyesi', 'Jiang Chengzi', 'Climb the Stork Tower'])

3) items() function

dictName.items() #Can output all items in the dictionary

>>> dict1.items()
dict_items([('Li Bai', 'Jingyesi') , ('Su Shi', 'Jiang Chengzi'), ('Wang Zhihuan', 'Deng Guanque Tower')])

4) get() function
        Read or call the value of a key in the dictionary. If you call it directly with dictName[key], an error will be reported if the key does not exist. Use dictName .get(key,"..."), if the key exists, the output corresponds to the value. If it does not exist, it will output "...". The second parameter of get() can be omitted. If not, it will output None if it does not exist.
In addition, the member operator in can be used to determine whether a key exists in the dictionary. Note here that only Determine the key, but not the value
>>> "Li Bai" in dict1
True
>> ;> "Jingyesi" in dict1
False

5) update(dictName2)
     dictName1.update(dictName2) #Equivalent to pasting dictionary 2 to dictionary 1, duplicate key corresponding values ​​are replaced and updated, and can be used to modify or add dictionary element

6) Others

     Pop(keyName) #Used to obtain the value corresponding to the specified key and delete this key-value pair.

     popitem() #Method is used to randomly pop up a key-value pair in the dictionary.
        (Note that the randomness here is actually false. It is the same as the list.pop() method, which also pops up the last key-value
pair in the dictionary. However, since the order in which key-value pairs are stored in the dictionary is agnostic, the popitem() method always pops the last key-value pair stored in the underlying storage.)

     copy()

     clear()

gather

        Sets in Python are the same as the concept of sets in mathematics. They are used to store non-repeating elements, that is, the elements in the set are allunique, different from each other.

        Formally, similar to a dictionary, a Python collection will place all elements in a pair of curly brackets {}, with adjacent elements separated by ",", as shown below: < a i=1> {element1,element2,...,elementn}

        In the same collection, only immutable data types can be stored, including integers, floating point types, strings, and tuples. Mutable data types such as lists, dictionaries, and sets cannot be stored, otherwise the Python interpreter will throw a TypeError error.

        There are two set types in Python, one is the set type set, the other is the  frozenset  type set, they are unique The difference is that the set type collection can add and delete elements, but the forzenset type collection cannot.

set:

        Python provides 2 methods of creating set collections, namely using {} to create and using the set() function to convert column
tables, tuples and other types of data into sets.

        Methods for adding and deleting elements:

        1)setname.add(element) 

        ​​​​​2)setname.remove(element)​​ #If the deleted element is not included in the collection, this method will throw a KeyError error

        Intersection (&), union (|), difference (-) and symmetric difference (^) operations can be performed between sets.

frozenset:

       ​ ​ frozenset() function:

        setName =   frozenset()             #setName is an empty frozenset

        setName = frozenset({element1,element2,…,elementn})   #setName is frozenset type

        ​​​​​setName2 = frozenset(setName1)​ #setName2 is frozenset type, setName1 is still set type

        frozenset has two main functions:                       1) When the set elements do not need to be changed, it is safer to use frozenset instead of set.         2) When some APIs require immutable objects, frozenset must be used instead of set. For example, the key of dict must be an immutable object, so only frozenset can be used; another example is that the set elements of set itself must be immutable, so set cannot contain set, and set can only contain frozenset.

Guess you like

Origin blog.csdn.net/chn_zx/article/details/131886344