Python data structures - dictionaries and collections

Posted by Raider on Mon, 13 Dec 2021 05:14:06 +0100

Author: AXYZdong Automation Engineering Male A little thinking, a little thinking, a little rationality! Set a small goal and try to become a habit! Meet better yourself in the most beautiful years! CSDN@AXYZdong , CSDN launch, axyzdong original The only blog update address is: AXYZdong's blog The homepage of station B is: AXYZdong's personal home page

Article catalog

Dictionaries

A dictionary is a data structure composed of a series of key value pairs.

Dictionary indexes can use different data types, not just integers. The index of the dictionary is called "key", and the key and its associated value are called "key value" pairs.

Each key in the dictionary is associated with a value

  1. The key must be a hash able value, such as string, numeric value, etc
  2. Value, which can be any object

1. Create a dictionary

Create a dictionary using curly braces {}.

>>> me = {'name':'axyzdong', 'age':'22'}
>>> me['name']
'axyzdong'
>>> 'My name is '+ me['name']
'My name is axyzdong'

Assign a dictionary to the me variable. The key values of this dictionary are 'name' and 'age'. The corresponding values of these keys are 'axyzdong' and '22'. These values can be accessed through their keys.

Dictionaries can use integers as keys.

>>> spam = {12345:'Luggage Combinaion', 42:'The Answer'}
>>> spam[42]
'The Answer'

2. Dictionaries and lists

Different from the list, the table items in the dictionary are not sorted, that is, there is no order of 'key value' pairs in the dictionary.

>>> spam1 = ['a','b','c']
>>> spam2 = ['b','a','c']
>>> spam1 == spam2
False
>>> spam3 = {1:'a', 2:'b', 3:'c'}
>>> spam4 = {2:'b', 1:'a', 3:'c'}
>>> spam3 == spam4
True
>>> 

3. Addition, deletion, modification and query

View element

>>> me = {'name':'axyzdong', 'age':'22'}
>>> me['name']
'axyzdong'

New element

>>> me = {}
>>> me['name']='axyzdong'
>>> me['age']='22'
>>> me
{'name': 'axyzdong', 'age': '22'}

Modify element

>>> me = {'name': 'axyzdong', 'age': '22'}
>>> me['age'] = '20'
>>> me
{'name': 'axyzdong', 'age': '20'}

Delete element

>>> spam = {1:'a', 2:'b', 3:'c'}
>>> spam.pop(1)
'a'
>>> spam
{2: 'b', 3: 'c'}
>>> del spam[2]
>>> spam
{3: 'c'}

4. Important methods

  • keys(), values() and items() methods

They return list like values corresponding to dictionary key values, values, and key value pairs: keys(), values(), and items(). The returned values are not real lists and cannot be modified. However, these data types (dict_keys, dict_vslues, and dict_items, respectively) can be used for the for loop.

>>> me = {'name': 'axyzdong', 'age': '22'}
>>> for i in me.keys():
	print(i)

name
age
>>> for j in me.values():
	print(j)

axyzdong
22
>>> for k in me.items():
	print(k)

('name', 'axyzdong')
('age', '22')

You can turn the return value into a real list through the list function.

>>> me = {'name': 'axyzdong', 'age': '22'}
>>> list(me.keys())
['name', 'age']
>>> list(me.values())
['axyzdong', '22']
>>> list(me.items())
[('name', 'axyzdong'), ('age', '22')]

Multiple assignment technique

>>> me = {'name': 'axyzdong', 'age': '22'}
>>> for i,j in me.items():
	print('Key:' + i + ' Value:' + j)

Key:name Value:axyzdong
Key:age Value:22
  • Check the dictionary for key, value, or key value pairs
>>> me = {'name': 'axyzdong', 'age': '22'}
>>> 'name' in me.keys()
True
>>> 'axyzdong' in me.values()
True
>>> ('name','axyzdong') in me.items()
True
  • get() method

The get() method has two parameters. The first parameter is the key to get its value; the second parameter is the alternate value returned if the key does not exist.

>>> me = {'name': 'axyzdong', 'age': '22'}
>>> 'My name is ' + me.get('name', 'Li Hua')
'My name is axyzdong'
>>> 'My name is ' + me.get('fiend', 'Li Hua')
'My name is Li Hua'  #When the 'friend' key does not exist, the standby value 'Li Hua' is returned
  • setdefault() method

The setdefault() method has two parameters. The first parameter is the key to check; the second parameter is the value to set if the key does not exist. (if the key exists, the method will return the value of the key)

me = {'name': 'axyzdong', 'age': '22'}
>>> me.setdefault('hobby','cycling')
'cycling'
>>> me
{'name': 'axyzdong', 'age': '22', 'hobby': 'cycling'}
>>> me.setdefault('name','Li Hua')
'axyzdong'
>>> me
{'name': 'axyzdong', 'age': '22', 'hobby': 'cycling'}

demo: calculates the number of occurrences of each character in the input string.

# -*- coding: utf-8 -*-
# @File : characterCount
# @Author : axyzdong
# @Time : 2021/11/25 21:28
# @Project : demo
message = str(input('message = '))
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character]+1

print(count)

Enter my name is axyzdong! In the interactive window to get the number of occurrences of each character.

message =  my name is axyzdong !
{' ': 5, 'm': 2, 'y': 2, 'n': 2, 'a': 2, 'e': 1, 'i': 1, 's': 1, 'x': 1, 'z': 1, 'd': 1, 'o': 1, 'g': 1, '!': 1}

pprint module to achieve beautiful printing

import pprint
message = str(input('message = '))
count = {}
for character in message:
    count.setdefault(character, 0)
    count[character] = count[character]+1

pprint.pprint(count)

Enter my name is axyzdong! In the interactive window, and the running results are as follows:

message = my name is axyzdong !
{' ': 4,
 '!': 1,
 'a': 2,
 'd': 1,
 'e': 1,
 'g': 1,
 'i': 1,
 'm': 2,
 'n': 2,
 'o': 1,
 's': 1,
 'x': 1,
 'y': 2,
 'z': 1}

aggregate

Sets in python are consistent with sets in mathematics. Duplicate elements are not allowed (i.e. the elements in the set are unique), and intersection, union, difference and other operations can be performed.

1. Create a collection

>>> set1 = {1,2,3}
>>> print(set1)
{1, 2, 3}
>>> set2 = set(range(1,10))
>>> set3 = set((1,2,3))
>>> print(set2,set3)
{1, 2, 3, 4, 5, 6, 7, 8, 9} {1, 2, 3}

2. Add and delete elements

>>> set1 = {1,2,3}     #Add element
>>> set1.add(4)
>>> set1
{1, 2, 3, 4}
>>> set1.update([7,8]) #Add element
>>> set1
{1, 2, 3, 4, 7, 8}
>>> if 7 in set1:      #Delete element
	set1.remove(7)	
>>> set1
{1, 2, 3, 4, 8}
>>> set2 = {'a', 'b', 'c'}
>>> set2.pop()		   #Randomly delete elements
'b'
>>> set2
{'a', 'c'}
>>> set2.clear()	   #Empty collection elements
>>> set2
set()

3. Set operation

  • Intersection, union, difference, symmetric difference (no re combination set)
>>> set1 = {1, 2, 3 ,'a'}
>>> set2 = {1, 'a', 'b', 'c'}
>>> print(set1.intersection (set2))  #intersection
{1, 'a'}
>>> print(set1.union(set2))			#Union
{1, 2, 3, 'c', 'b', 'a'}
>>> print(set1.difference (set2))	#Difference set
{2, 3}
>>> print(set1.symmetric_difference (set2))	#Symmetry difference
{2, 3, 'c', 'b'}
>>> print(set1 & set2)	#intersection
{1, 'a'}
>>> print(set1 | set2)	#Union
{1, 2, 3, 'c', 'b', 'a'}
>>> print(set1 - set2)	#Difference set
{2, 3}
>>> print(set1 ^ set2)	#Symmetry difference
{2, 3, 'c', 'b'}
  • Judgment subset and superset
>>> print(set2.issubset(set1))
False
>>> print(set1.issuperset(set2))
False

  that's all for this sharing