Dictionary collection public operation

Keywords: Python Pycharm

Circular traversal of dictionary

key traversing dictionary

dict = {"k1": "v1", "k2": "v2", "k3": "v3"}
keys = dict.keys()
print(keys)
for key in keys:
    print(key)

Note: key refers to the key of the dictionary, for example: 'k1', 'k2', 'k3'

Traverse the value of the dictionary

dict = {"k1": "v1", "k2": "v2", "k3": "v3"}
values = dict.values()
print(values)
for value in values:
    print(value)

Note: value refers to the value of the dictionary, for example: 'v1', 'v2', 'v3'

Traversing dictionary elements

dict = {"k1": "v1", "k2": "v2", "k3": "v3"}
items = dict.items()
print(items)
  • The items method recombines the elements in the dictionary:
    • A list is created first
    • If there are several elements in the dictionary, several tuples are added to the list
    • Take the key of the element in the dictionary as the first element in the element and the value as the second element of the tuple

Traverse the key value pairs of the dictionary

dict = {"k1": "v1", "k2": "v2", "k3": "v3"}
items = dict.items()
for item in items:
    print(f'{item[0]}={item[1]}')

Key value pair: each key is followed by a corresponding value. When the corresponding key is pressed, the corresponding result will be output

k1=v1
k2=v2
k3=v3

aggregate

Create collection

Use {} or set() to create a collection, but only set() if you want to create an empty collection. Because {} is used to create an empty dictionary

s1={10,20,30,40,50}
print(s1)   #{40, 10, 50, 20, 30}  

s2={10,30,20,10,30,40,30,50}
print(s2)   #The {40, 10, 50, 20, 30} set automatically removes duplicate data

s3=set('abcdefg')
print(s3)   #{'c', 'b', 'a', 'e', 'f', 'd', 'g'}

s4=set()    
print(type(s4)) 	#< class' set '> creates an empty set

s5={}   
print(type(s5)) 	#< class' dict '> create an empty dictionary

characteristic:
1. The collection can remove duplicate data
2. The set data is out of order, so subscripts are not supported

Collection common operation methods

  1. Add data
  • add()
s3={'a','b','c'}
s3.add('d')	#increase
s3.add('b')	#Automatically remove duplicate values
print(s3)	#{'B', 'a','d ',' C '} output results are out of order

Note: because the collection has the function of removing duplicates, adding existing elements to the collection will be automatically removed by the collection

  • update(), the appended data is a sequence
s1 = {10, 20}
# s1.update(100) # report errors
s1.update([100, 200])
s1.update('abc')
print(s1)	#{'c', 100, 'b', 200, 10, 'a', 20}
  1. Delete data
  • remove(), deletes the specified data in the collection. If the data does not exist, an error will be reported
s1 = {10, 20}
s1.remove(10)
print(s1) 	#{20}
s1 = {10, 20}
s1.remove(30)
print(s1)	#report errors
  • pop(), then deletes a data in the collection and returns the data
s1 = {10, 20, 30, 40, 50}
del_num = s1.pop()
print(del_num)
print(s1)	#{10, 50, 20, 30} is deleted

Find data

  • In: judge whether the data is in the set sequence
  • Not in: judge that the data is not in the set sequence
s1 = {10, 20, 30, 40, 50}
print(10 in s1)	#True 10 prints true in the sequence
print(60 in s1)	#False 60 does not print false in the sequence
print(10 not in s1)	#False 10 prints false in the sequence
print(60 not in s1)	#True 60 does not print true in the sequence

Public operation

Common operator

operatordescribeSupported container types
+mergeString, list, tuple
*copyString, list, tuple
inDoes the element existString, list, tuple, dictionary
not inDoes the element not existString, list, tuple, dictionary

+If both sides of the sign are numbers, it means addition, but it is used between strings, lists and tuples

print('3' + '5')	#35 addition
print('a' + 'b' + 'c')	#abc addition

l1 = ['a', 'b', 'c']
l2 = [10, 20, 30]
print(l1 + l2)	#['a ',' B ',' C ', 10, 20, 30] merge

t1 = (10, 20)
t2 = (30, 40)
print(t1 + t2)	#(10, 20, 30, 40) consolidation

If there are numbers on both sides of the * sign, it means addition, but it is used between strings, lists and tuples

str = '🙂'
print(str * 20)	#🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂
l1 = ['a', 'b']
print(l1 * 5)	#['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
  • In or not in
    judge
str1 = 'aSDJFLKASDJFLASDJSD'
print('F' in str1)	#True

l1 = ['Xiao Ming', 'Xiao Hong', 'Xiaolan', 'Xiao Li']
name = 'Xiao Ming'
print(name in l1)	#True

Public method

functiondescribe
len()Calculate the number of elements in the container
Del or del()delete
max()Returns the maximum value of the element in the container
min()Returns the minimum value of the element in the container
range(start,end, step)Generate a number from start to end in step for the for loop
enumerate()The function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop.
  • len()
#character string
str1 = 'abcdefg'
print(len(str1))  # 7
#aggregate
s1 = {10, 20, 30}
print(len(s1))  # 3
#Dictionaries
dict1 = {'name': 'Rose', 'age': 18}
print(len(dict1))  # 2
  • del()
#list
list1 = [10, 20, 30, 40]
del(list1[0])
print(list1)  # [20, 30, 40]
  • max and min
l1 = [20, 22, 44, 1, 55, 77]
print(max(l1))	#77
#If it is a word comparison, compare the initials
l3 = ['zab', 'hello', 'word', 'nice', 'very']
print(max(l3))	#zab
#max cannot compare two different types of data
l2 = [1, 5, 33, 'a', 'v', 'z']
print(max(l2))	#report errors
  • range
for i in range(1, 10, 3):
    print(i)	#1 4 7

Note: the sequence generated by range() does not contain the end number.

  • enumerate()
    • Syntax: enumerate (traversable object, start=0)

Note: the start parameter is used to set the starting value of the subscript of traversal data, which is 0 by default.

list1 = ['a', 'b', 'c', 'd', 'e']
for item in enumerate(list1):
    print(item)	#(0,'a')(1,'b')(2,'c')(3,'d')(4,'e')

Container type conversion

  • tuple()
    Function: convert a sequence into tuples
list1 = [10, 20, 30, 40, 50, 20]
s1 = {100, 200, 300, 400, 500}
print(tuple(list1))	#List tuple (10, 20, 30, 40, 50, 20)
print(tuple(s1))	#Set tuple (100, 200, 300, 400, 500)
  • set()
    Function: convert a sequence into a set
list1 = [10, 20, 30, 40, 50, 20]
t1 = ('a', 'b', 'c', 'd', 'e')
print(set(list1))	#List to set {40, 10, 50, 20, 30}
print(set(t1))	#Tuple to set {'a','d ',' C ',' B ',' e '}
  • list()
    Function: convert a sequence into a list
t1 = ('a', 'b', 'c', 'd', 'e')
s1 = {100, 200, 300, 400, 500}
print(list(t1))	#Tuple to list ['a ',' B ',' C ','d', 'e']
print(list(s1))	#Set transfer list [100, 200, 300, 400, 500]

be careful:

  1. Collection can quickly complete list de duplication
  2. Collection does not support subscripts

Posted by somo on Thu, 09 Sep 2021 12:23:20 -0700