Fortune Telling Collection - Comprehensive fortune-telling - Python is actually a very simple dictionary and collection in Chapter 10.

Python is actually a very simple dictionary and collection in Chapter 10.

The lists and tuples mentioned above are ordered sequences, while dictionaries and collections belong to unordered sequences, that is, elements cannot be manipulated by indexes.

10. 1 dictionary

Syntax format:

Dictionary = {key 1: value 1, key2: value2, key3: value3, ..., key n: value n}

Where dictionary is the dictionary name, key represents the key of the element, and value represents the value of the element. Keys and values must appear in pairs.

For example:

& gt& gt& gtdict 1 = { 'abc': 123,98.6: 37 }

& gt& gt& gt dictionary 1

{'abc': 123,98.6: 37}

It can be seen that keys can be strings, numbers or tuples, but they must be unique; The value can be of any data type and is not required to be unique.

1, the method of creating a dictionary

Method 1: Give both keys and values, that is, in the form of "keyword parameters".

Dictionary = dict (key1= value1,key2=value2, ... key n = value n).

Note: The keys here must conform to the naming rules of Python identifiers.

Example:

First create a dictionary using "{0}":

& gt> dict1= {1:'one', 2:' two', 3:' three', 4:' four', 5:' five'}

& gt& gt& gt dictionary 1

{1:' one', 2:' two', 3:' three', 4:' four', 5:' five'}

Then create it as a "keyword parameter":

> > > dict1= dict (1=' one', 2=' two', 3=' three', 4=' four', 5=' five').

Syntax error: the expression cannot contain assignment. Maybe you mean "= ="?

Creation failed because the key does not conform to the naming rules of Python identifiers. As mentioned earlier, identifiers cannot be represented by numbers, nor can they start with numbers.

Now, modify the key as follows:

> > > dict1= dict (n1=' one', n2=' two', n3=' three', n4=' four', n5=' five') # number is preceded by a character "n".

& gt& gt& gt dictionary 1

{'n 1':' one',' n2':' two',' n3':' three',' n4':' four',' n5':' five'}

Method 2: Use existing tuples and lists to create a dictionary through mapping function.

Format: dictionary = dict (zip (tuple key, list value))

Example:

& gt& gt& gt tuple key = ('N 1',' N2',' N3',' N4',' N5') # key is in tuple order.

> > > listvalue = ['one',' two',' three',' four',' five'] # values are listed in the order.

& gt& gt& gtdict 1=dict(zip(tuplekey,listvalue))

& gt& gt& gt dictionary 1

{'n 1':' one',' n2':' two',' n3':' three',' n4':' four',' n5':' five'}

Note: the tuple(listname) function can convert a list into a tuple, and the list(tuplename) function can convert a tuple into a list.

2. Access the dictionary by keys.

Directly get the value of the element corresponding to the key.

& gt& gt& gtdict 1['n2']

2'

Use the get () method

& gt& gt& gtdict 1.get('n2 ')

2'

The get () method can also accept parameters and return a string if the key to be accessed does not exist. For example:

& gt& gt& gtdict 1.get('n0',' not found! ) # When the key to be searched does not exist, return' Not found! '

"I can't find it!"

Step 3 consult the dictionary

Use the items () method of the dictionary object to get a list of key-value pairs of the dictionary.

& gt& gt& gt For the items in dict 1.items ():

Print (items)

('n 1',' one')

(“n2”,“II”)

("n3", "three")

("n4", "Four")

("n5", "V")

You can also get specific keys and values for each element, such as:

& gt& gt& gt For key, the value in dict 1.items ():

Print (key, "corresponding to", value)

N 1 corresponds to one

N2 is equivalent to two.

N3 is equivalent to three.

N4 corresponds to four.

N5 corresponds to five.

4. Add, modify and delete dictionary elements.

Use the following statement to modify the value of the element if the specified key exists; If the specified key does not exist, an element is added. For example:

& gt> dict1['n6'] =' six' # key' n6' does not exist, so this element is added.

& gt& gt& gt dictionary 1

{'n 1':' one',' n2':' two',' n3':' three',' n4':' four',' n5':' five',' n6':' six'}

& gt> dict1['n4'] =' é' # key' n4' exists, so this element is modified.

& gt& gt& gt dictionary 1

{'n 1':' one',' n2':' two',' n3':' three',' n4':' four',' n5':' five',' n6':' six'}

5. Establish a dictionary by deduction.

Random import

dict 1 = { I:random . randint( 1, 100) for i in range(5)}

# The key of the generated element is an integer from 0 to 5, and the value is a random number between 1 and 100.

Print (dict 1)

Running results: {0: 28, 1: 59, 2: 79, 3: 30, 4: 88}

10.2 sets

Set is a very important concept in mathematics, which has three basic attributes: certainty, mutual difference and disorder. In Python, a set also has these three basic attributes, among which certainty means that the object is either an element of the set or not; Reciprocity means that elements in a set cannot be repeated; Disorder means that the elements in a set can change their positions at will, regardless of order.

1, creation of set

Create directly with "{0}"

& gt& gt& gtSet 1={' Spring',' Summer',' Autumn',' Winter'}

& gt& gt& gtset 1

{'Autumn',' Spring',' Winter',' Summer'}

& gt& gt& gt Set 2 = {3,2, 1, 4,5}

& gt& gt& gt set 2

{ 1, 2, 3, 4, 5}

Create a collection using existing lists and tuples.

& gt> list1= ['East',' South',' West',' North']

& gt& gt& gtset3=set(list 1)

& gt& gt& gt set 3

{'South',' East',' North',' West'}

Create a copy from an existing collection.

& gt& gt& gt set 3

{'South',' East',' North',' West'} #set3 and set4 have the same value.

& gt& gt& gt Set 4 = Set 3

& gt& gt& gt set 4

{'South',' East',' North',' West'}

& gt> Set4.add ('in') # Add elements to set4.

& gt& gt& gt set 4

{'West',' Middle',' East',' South',' North'} # This is easy to understand.

& gt& gt& gt set 3

{'West',' Middle',' East',' South',' North'} # Fancy it? Why does Set3 change?

Look at an example of a simple variable:

& gt& gt& gta=2

& gt& gt& gtb=a # Is it similar to the previous set4=set3?

& gt& gt& gtb+= 1

& gt& gt& gtb

three

& gt& gt& gta

2 # but the value of a has not changed.

From the comparison of the values of sets set3 and set4 above with those of simple variables A and B, it is not difficult to find that set3 and set4 are objects pointing to the same address, while variable A and variable B point to different addresses. The statement b=a passes the value of A to B instead of the address of A. Lists, tuples and dictionaries all have the same properties as sets.

Therefore, it is more appropriate to call set4 a copy of set3.

2. Add and delete elements

& gt& gt& gt set 3

{'South',' East',' North',' West'}

& gt& gt& gtSet3.add ('in') # Add element

& gt& gt& gt set 3

The elements in the {'West',' Middle',' East',' South' and' North'} # sets are out of order, so don't worry about the change of order.

& gt>> set3.remove ('in') # delete element

& gt& gt& gt set 3

{'West',' East',' South',' North'}

3. Set operation

Set operations include intersection (&; ), union (|) and difference (-) are consistent with the set operation in mathematics.

& gt& gt& gtSet3={' South',' East',' North',' West'}

& gt& gt& gtSet4={' West',' Middle',' East',' South',' North'}

& gt& gt& gtset3 & set 4 # takes the intersection of set 3 and set 4.

{'West',' South',' North',' East'}

& gt& gt& gtSet3 | set4 # takes the union of set 3 and set 4.

{'Middle',' South',' North',' West',' East'}

& gt& gt& gtSet3-set4 # takes the difference between Set3 and set4, that is, set3 has more elements than set4.

Set ()

& gt& gt& gtSet4 -set3 # takes the difference between Set4 and set3, that is, set4 has more elements than set3.

{'in'}