python basic deliberate practice -- Task 6 dictionary and collection

Day 8

I. dictionary

  • A dictionary is another variable container model and can store any type of object.
  • Each key value key = > value pair of the dictionary is separated by colon: comma is used between each pair, and the whole dictionary is included in curly bracket {}, with the format as follows:
diction = {key1 : value1, key2 : value2 }
  • The key must be unique, but the value is not. Value can take any data type, but the key must be immutable, such as string, number or tuple.
  • Here is a simple example of a dictionary:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
# perhaps
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
1) access the values in the dictionary
  • To access the values in the dictionary, we need to put the corresponding keys in square brackets, as shown in the following example:
dict = {'Name': 'Tim', 'Age': 12, 'Class': 'No.1'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
'''
//Output:
dict['Name']:  Tim
dict['Age']:  12
'''
  • If you access data with a key that is not in the dictionary, an error will be output.
2) modify dictionary
  • The way to add new content to the dictionary is to add new key / value pairs, modify or delete the existing key / value pairs as follows:
dict = {'Name': 'Jim', 'Age': 12, 'Class': 'No.1'}
 
dict['Age'] = 17               # Update Age
dict['School'] = "Senior high school"     # Add information

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
'''
dict['Age']:  17
dict['School']:  Senior high school
'''
3) delete dictionary elements
  • Can delete a single element can also empty the dictionary, empty only one operation. del command is used to delete a dictionary, as shown in the following example:
dict = {'Name': 'Tim', 'Age': 12, 'Class': 'No.1'}
 
del dict['Name']   # Delete key 'Name'
dict.clear()       # Empty dictionary
del dict           # Delete dictionary

print ("dict['Age']: ", dict['Age'])
  • The dictionary will no longer exist after running, so there will be errors in the final output.
4) characteristics of dictionary key

Dictionary values can be any python object, either standard or user-defined, but not key. There are two important points to keep in mind:

  • Two occurrences of the same key are not allowed. If the same key is assigned twice during creation, the latter value will be remembered, as shown in the following example:
dict = {'Name': 'Tim', 'Age': 12, 'Name': 'Bob'}
 
print ("dict['Name']: ", dict['Name'])
#  dict['Name']:  Bob
  • The key must be immutable, so it can be used as a number, string or tuple, but not as a list. For example:
dict = {['Name']: 'Runoob', 'Age': 7}
 
print ("dict['Name']: ", dict['Name'])
# Output error!
5) dictionary built-in functions and methods
  • The dictionary contains the following built-in functions:
  • The dictionary contains the following built-in methods:

Two, set

  • A set is an unordered sequence of distinct elements.
  • You can use curly braces {} or the set() function to create a collection. Note: to create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.
  • Its creation format is:
parame = {value01,value02,...}
//perhaps
set(value)
1) create a collection:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  # {'banana', 'apple', 'pear', 'orange'}
  • Use the set(value) factory function to convert a list or tuple into a set:
a = set('abracadabra')
print(a)  
# {'r', 'b', 'd', 'c', 'a'}

b = set(("Google", "Lsgogroup", "Taobao", "Taobao"))
print(b)  
# {'Taobao', 'Lsgogroup', 'Google'}

c = set(["Google", "Lsgogroup", "Taobao", "Google"])
print(c)  
# {'Taobao', 'Lsgogroup', 'Google'}
  • Operations can also be performed between two sets:
a = set('abracadabra')
b = set('alacazam')
print(a)      # {'a', 'r', 'b', 'c', 'd'}
print(a - b)  # {'r', 'd', 'b'}                            # Elements contained in set a but not contained in set b
print(a | b)  # {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}   # All elements contained in set a or b
print(a & b)  # {'a', 'c'}                                 # Elements contained in sets a and b
print(a ^ b)  # {'r', 'd', 'b', 'm', 'z', 'l'}             # Elements different from a and b
2) access the values in the set
  • You can use for to read out the data in the collection one by one.
thisset = set(['Google', 'Baidu', 'Taobao'])
for item in thisset:
    print(item)

# Baidu
# Google
# Taobao
  • You can also use in or not in to determine whether an element already exists in the collection.
thisset = set(['Google', 'Baidu', 'Taobao'])
print('Taobao' in thisset)        # True
print('Facebook' not in thisset)  # True
3) built in method of set
Built-in method Method description
set.add(elmnt) Used to add elements to a collection, if the added element already exists in the collection, no action is taken.
set.remove(item) Removes the specified element from the collection.
set.update(set) Used to modify the current collection. You can add a new element or collection to the current collection. If the added element already exists in the collection, the element will only appear once, and repeated elements will be ignored.
set.intersection(set1, set2 ...) Used to return elements contained in two or more collections, that is, intersections.
set.union(set1, set2...) Returns the union of two sets, that is, the elements that contain all sets, and the repeated elements only appear once.
set.difference(set) Returns the difference set of a set, that is, the returned set element is contained in the first set, but not in the second set (the parameter of the method).
set.issubset(set) It is used to determine whether all elements of the collection are included in the specified collection. If yes, it returns True; otherwise, it returns False.
set.issuperset(set) It is used to determine whether all elements of the specified collection are included in the original collection. If yes, it returns True; otherwise, it returns False.
  • Here are some examples:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")        # Additive elements
print(fruits)  
# {'orange', 'cherry', 'banana', 'apple'}

fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")     # Removing Elements
print(fruits)  # {'apple', 'cherry'}

x = {"apple", "banana", "cherry"}
y = {"google", "baidu", "apple"}
x.update(y)                # Modifying elements
print(x)  
# {'cherry', 'banana', 'apple', 'google', 'baidu'}

a = set('abracadabra')
b = set('alacazam')
print(a)  # {'r', 'a', 'c', 'b', 'd'}
print(b)  # {'c', 'a', 'l', 'm', 'z'}
# intersection
print(a & b)  # {'c', 'a'}
c = a.intersection(b)
print(c)  # {'a', 'c'}
# Union
print(a | b)  # {'l', 'd', 'm', 'b', 'a', 'r', 'z', 'c'}
c = a.union(b)
print(c)  # {'c', 'a', 'd', 'm', 'r', 'b', 'z', 'l'}
# Difference set
print(a - b)  # {'d', 'b', 'r'}
c = a.difference(b)
print(c)  # {'b', 'd', 'r'}

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)  # True
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
z = x.issubset(y)
print(z)  # False

x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)  # True
x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)  # False
4) immutable set
  • frozenset([iterable]) will return a frozen collection. After freezing, the collection cannot add or delete any elements. For example:
s = frozenset('basketball')
print(s)
# frozenset({'s', 'k', 't', 'e', 'l', 'a', 'b'})

Remarks:

Learning References:
https://www.runoob.com/python3/python3-set.html
https://mp.weixin.qq.com/s?__biz=MzIyNDA1NjA1NQ==&mid=2651011465&idx=1&sn=2f4a24746ed6c6d42e04f2434bcd27b4&chksm=f3e35e11c494d7072fbb215f2ca548801338306f65d9ab78723c2ff02290484b0b983a2879c7&mpshare=1&scene=1&srcid=&sharer_sharetime=1572129397658&sharer_shareid=8c49d4226c319addceef298b781f6bb7&key=f0572ec07140f16088698c0ef9ed666bd510f1eb2e674d5e00b33d1ef29a7c86056b92736f977e9dae2bd5b939807d99ec77a9cee4e42beb6e266ec66ae7c9112c52ff8115b96fe6c820da78b2dddcd0&ascene=1&uin=MTgxNzI3MTY0MQ%3D%3D&devicetype=Windows+10&version=62060841&lang=zh_CN&pass_ticket=CTTViZgHQX3FG9pptB%2FT82I3eIlTTl%2FR8oxPUQqTT2Bp2DW3cDe7M5%2Ff05feFRLl

Keywords: Google Python Windows

Added by NDF on Sun, 27 Oct 2019 12:54:12 +0200