Deliberate practice -- Python basic Task06. Dictionaries and collections

Posted by COOMERDP on Sat, 26 Oct 2019 20:27:02 +0200

Deliberate practice -- Python basic Task06. Dictionaries and collections

I. dictionary

  • Create Dictionary: you can use curly braces or the dict() function to create a dictionary.
  • key in dictionary is not allowed to be duplicate.
  • Delete key value pair: use del statement.
  • In or not in: determines whether the dictionary contains the specified key.
  • Clear() method: clear all key value pairs in the dictionary. After executing the clear() method on the dictionary, the dictionary will become an empty dictionary.
  • Get() method: get the value according to the key (equivalent to the enhanced version of the square bracket syntax -- when using the square bracket syntax to access the key that does not exist, the dictionary will cause a KeyError; however, get() method will return None, which will not cause an error).
  • update() method: use the key value pair contained in a dictionary to update the existing dictionary.
  • items(): get all key value pairs in the dictionary.
  • keys(): get all the key s in the dictionary.
  • values(): gets all value s in the dictionary.
    After items(), keys(), and values() are used, the returned dict_items, dict_keys, and dict_values objects must be converted into a list through the list() function and returned.
  • pop() method: get the value corresponding to the specified key, and delete the key value pair.
  • popitem() method: randomly pop up a key value pair in the dictionary.
  • setdefault() method: get the value of the corresponding value according to the key (if the key does not exist, Python will automatically set a default value).
  • fromkeys() method: create a dictionary with multiple keys given, and the value corresponding to these keys is None by default; you can also use an extra parameter as the default value.
  • Format string using dictionary
#Using key in a string template
temp = 'The title of the book is:%(name)s,Price is:%(price)010.2f,The press is:%(publish)s'
book = {'name':'mathematical analysis','price':'42.30','publish':'Higher Education Press'}
#Use dictionary to pass in value for key in string template
print(temp % book)
  • Use the for in loop to traverse the dictionary: items(), keys(), and value() are required
my_list = {'Chinese':130,'Math':148,'English':146}
for key,value in my_list.items():
	print('key:',key)
	print('value:',value)
for key in my_list.keys():
	print('key:',key)
	#Then get value through key
	print('value:',my_list[key])
for value in my_list.values():
	print('value:',value)		

Two, set

  • set creation: enclose the contained elements in curly braces.
  • Features of set set set: 1.set does not record the order of adding elements; 2. Elements are not allowed to repeat; 3.set set is a variable container (the elements of frozenset corresponding to set are immutable)
  • Enter [e for E in dir (set) if not e.startswitch ('")] to see all the methods of set set set
  • The usage of set set method
#Using curly braces to build set sets
c = {'naruto'}
#Additive elements
c.add('boruto')
c.add(886)
#Delete specified element
c.remove(886)
#Determine whether the specified string is included
print("c Whether the collection contains'naruto'Character string:",('naruto' in c)) #Output True
#Use the set() function (constructor) to create a set set
a = set()
a.add(1)
a.add('KFC')
#Use the issubset() method to determine whether it is a subset
print("a Set is c Subset of?",a.issubset(c)) #Output False
#Using the issubset() method works the same as the < = operator
print("a Set is c Subset of?",(a <= c)) #Output False
#Using issuperset() method to judge whether it is a parent set
print("c Whether the collection contains all a Set?,c.issuperset(a))"  #Output False
#The issuperset() method has the same effect as the > = operator
print("c Whether the collection contains all a Set?,(c>=a))"  #Output False
#Subtracting the elements in the books set from the c set does not change the c set itself
result1 = c - a
print(result1)
#The difference() method is also used to subtract sets, which is exactly the same as using "-" to perform operations.
result2 = c.difference(a)
print(result2)
#Subtracting the elements of a set from c set, changing c set itself
c.difference_update(a)
print("c Elements of collection:",c)
#Delete all elements in c set
c.clear()
#Create a new collection
d = {'raruto',555,666}
#Calculate the intersection of two sets without changing the d set itself
inter1 = d & c
print(inter1)
#The intersection() method is also used to obtain the intersection of two sets, which is exactly the same as using & to perform operations.
inter2 = d.intersection(c)
print(inter2)
#Calculating the intersection of two sets, changing the d set itself
d.intersection_update(c)
print("d Elements of collection:",d)
#Wrap the range object as a set set
e = set(range(5))
f = set(range(3,7))
#XOR two sets
xor = e ^ f
print('e and f implement xor Results:',xor)
#Calculate the union of two sets without changing the e set itself
un = e.union(f)
#Calculate the union of two sets, change e itself
e.update(f)
  • In all set sets, methods that can change the set itself are not supported by frozen set; in all set sets, methods that do not change the set itself are supported by frozen set.
  • The main functions of frozenset are as follows:
    1. When the set element does not need to be changed, it is safer to use frozen instead of set.
    2. When some API s need immutable objects, they must replace set with hazenset. Such as the key of dict and the set element of set itself.

Topics: Python