0x07 - dictionaries and collections in Python

Posted by sleepingdanny on Wed, 08 Dec 2021 03:12:36 +0100


catalog: 0x00 - Python learning notes

Dictionaries

When the index is not easy to use, a dictionary is born. It is the only mapping type in Python. It is represented by key value pairs. A key value pair is called an image, and in some places it is also called an associative array
There is no order in the dictionary. It will be automatically stored according to the character priority
Like list, tuple and string, they all belong to mapping type, and their indexes (0, 1, 2,...) are independent of content

  • establish
    In Python, braces are used to represent a dictionary
>>> dict1 = {'img':'1.png', 'key':'yes', 'path':'flag'}
>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict3 = dict(img='1.png', key='yes', path='flag')
>>> dict4 = {}
  • call
>>> print(dict1['path'])
flag
  • add to
    Assigning a value to a nonexistent index in the sequence will directly report an error, but assigning a value to a nonexistent key in the dictionary will automatically add this key value pair (modify it if it exists)
>>> dict4 = {}
>>> dict4['web'] = 'dog!!!'
>>> dict4
{'web': 'dog!!!'}
  • Factory function
    A factory function is a function that can create a type similar to a factory
    They are: str(), int(), list(), tuple(), dict()

Built in method

  • fromkeys(s[,v])
    This method creates and returns a new dictionary. The first parameter is the key, and the second parameter is the value (which can be omitted)
    The dictionary as like as two peas is built in exactly the same value.
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3), (1,'asd'))
{1: (1, 'asd'), 2: (1, 'asd'), 3: (1, 'asd')}
  • keys()
    Return key
>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict2.keys()
dict_keys(['img', 'key', 'path'])
  • items()
    Return image
>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict2.items()
dict_items([('img', '1.png'), ('key', 'yes'), ('path', 'flag')])
  • get()
    Use the index key to access a value. If the key does not exist, no error will be reported (mainly for users)
  • clear()
    Empty a dictionary
>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict2.clear()
>>> dict2
{}

You can use empty dictionary, but it is not rigorous

>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict3 = dict2
>>> dict2 = {}
>>> dict2
{}
>>> dict3
{'img': '1.png', 'key': 'yes', 'path': 'flag'}
  • copy()
    Shallow copy

Assignment is a label directly attached to the value, which can be understood as another name
A shallow copy is a copy of a new piece of data

>>> dict2 = dict((('img','1.png'),('key','yes'),('path','flag')))
>>> dict3 = dict2
>>> dict4 = dict2.copy()
>>> id(dict2)
1918018041472
>>> id(dict3)
1918018041472
# You can see that the above two are the same, but their names are different
>>> id(dict4)
1918018684288
  • pop()
    Pop up a value and keep other values
>>> dict1 = {1:'one', 2:'two', 3:'three', 4:'four'}
>>> dict1.pop(1)
'one'
>>> dict1
{2: 'two', 3: 'three', 4: 'four'}
  • popitem()
    Pop up a value randomly
>>> dict1 = {1:'one', 2:'two', 3:'three', 4:'four'}
>>> dict1.popitem()
(4, 'four')
>>> dict1
{1: 'one', 2: 'two', 3: 'three'}
  • update()
    Update a dictionary with the mapping relationship of the dictionary
>>> dict1 = {1:'one', 2:'two', 3:'three', 4:'four'}
>>> a = {1:'asdasdasd'}
>>> dict1.update(a)
>>> dict1
{1: 'asdasdasd', 2: 'two', 3: 'three', 4: 'four'}

aggregate

Collections are also represented by braces

>>> set1 = {1,2,3,4,5,6}
>>> type(set1)
<class 'set'>

The set satisfies disorder and reciprocity

  • establish
    Create directly with braces
    Create using the set() factory function
>>> set1 = set((1,2,3,4,5,6,8,5,2,1,2,4,2,2))
>>> set1
{1, 2, 3, 4, 5, 6, 8}
  • duplicate removal
>>> list1 = [1,2,1,2,4,4,5,6,3,3,2,1,1]
>>> list1 = list(set(list1))
>>> list1
[1, 2, 3, 4, 5, 6]
  • judge
    You can use for to take out the elements in the collection one by one, or you can use in and not in to judge
>>> set1 = set((1,2,3,4,5,6,8,5,2,1,2,4,2,2))
>>> 2 in set1
True
>>> '2' in set1
False
  • Add and remove
>>> set1 = set((1,2,3,4,5,6,8,5,2,1,2,4,2,2))
>>> set1
{1, 2, 3, 4, 5, 6, 8}
>>> set1.add(10)
>>> set1
{1, 2, 3, 4, 5, 6, 8, 10}
>>> set1.remove(1)
>>> set1
{2, 3, 4, 5, 6, 8, 10}
  • Frozen: frozen
    Immutable set: the data in the immutable set cannot be changed
>>> set1 = frozenset((1,2,3,4))
>>> set.add(1)
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    set.add(1)
TypeError: descriptor 'add' for 'set' objects doesn't apply to a 'int' object

Topics: Python Back-end