Test questions and answers after lecture 026 of FIsh forum "zero foundation introduction to learning Python"

Posted by Anthony_john5 on Thu, 27 Jan 2022 10:04:02 +0100

FIsh forum "zero foundation introduction to learning Python" | lesson 026: Dictionary: when the index is not easy to use 2 | after class test questions and answers

Test questions

  1. Does Python's Dictionary support one Key and multiple values?
    Not supported. Assigning the same key again will directly overwrite the previous value.
    1. In the dictionary, what happens if you try to assign a value to a Key that does not exist?
    The corresponding Key will be automatically created and the corresponding Value will be added.
    2. Membership operators (in and not in) can check whether an element exists in the sequence. Of course, they can also be used to check whether a Key exists in the dictionary. Which is more efficient? Why?
    Checking whether a Key exists in a dictionary is more efficient than checking whether a specified element exists in a sequence. Because the principle of the dictionary is to use the hash algorithm for storage, one step in place, and there is no need to use the search algorithm for matching, the time complexity is O (1), and the efficiency is very high.
    3. Does Python have type restrictions on keys and values?
    Python has relatively strict requirements for keys. They must be Hash objects and cannot be variable types (including variables, lists, dictionaries, etc.).
    However, python has no restrictions on values. They can be any Python object.
    If you don't know the principle of hash and the storage principle of dictionary, it is recommended to read this article organized by little turtle for you: do you know how Python's Dictionary (Dict) is stored? ( http://bbs.fishc.com/thread-45016-1-1.html )
    For Python, the Key must be hashable, in other words, the unique address can be calculated through the hash function. Can I use a variable as a Key? Definitely not. Because variables can change at any time, it does not comply with the hashable principle!

    Similarly, lists, dictionaries and collections are variable, so they cannot be used as keys.

A friend may ask, what about Yuanzu? Should Yuanzu always remain the same?

In fact, it is not. Because variable factors such as lists can be stored in Yuanzu, if you really want to use Yuanzu as the Key of the dictionary, you must restrict Yuanzu: tuples can be used as effective keys in the dictionary only when they include immutable elements such as numbers and strings.

In addition, it should be noted that Python's hash algorithm obtains the same result for the same value, that is, the values of 12315 and 12315.0 are the same, and they are considered to be the same Key.
4. Please visually check what the dictionary dict1 contains after the following code is executed?
**fromkeys() * * syntax:

dict.fromkeys(seq[, value])

The fromkeys() function is used to create a new dictionary. The element in seq sequence is used as the key of the dictionary. Value is the initial value corresponding to all keys of the dictionary.
parameter
seq – dictionary key value list.
Value – optional parameter to set the value of key sequence (seq).
Return value
This method returns a new dictionary.

seq = ('Google', 'Runoob', 'Taobao')
 
dict = dict.fromkeys(seq)
print "The new dictionary is : %s" %  str(dict)
 
dict = dict.fromkeys(seq, 10)
print "The new dictionary is : %s" %  str(dict)

Output results:
The new dictionary is : {'Google': None, 'Taobao': None, 'Runoob': None}
The new dictionary is : {'Google': 10, 'Taobao': 10, 'Runoob': 10}

  1. If you need to copy the dictionary dict1 = {1: 'one', 2: 'two', 3: 'three'} to dict2, what should you do?
    dict2 = dict1.copy(),
    be careful:
    dict2 = dict1. In Python, it just copies the reference of the object.

use one's hands

  1. Try to write a user login program (this time try to encapsulate the function into a function), and the program implementation is shown in the figure:

    Reference code:
def showMenu():
    prompt = '''
|--- New user: N/n ---|
|--- Login account: E/e ---|
|--- Launch procedure: Q/q ---|
|--- Please enter the instruction code:'''
    print(prompt)


def CreateUser(info):
    name = input("enter one user name:")
    while name in info:
        name = input("The user name requested to create already exists, please re-enter:")
    password = input("Please input a password:")
    info[name] = password
    return info


def login(info):
    name = input("enter one user name:")
    while name not in info:
        name = input("The user name requested to log in does not exist, please re-enter:")
    while input("Please input a password:") != info[name]:
        print("Wrong password entered\n")
    print("Welcome to xx system")


###Main function
showMenu()
info = {}
while 1:

    order = input("Please enter instructions:")
    if order.isalpha() == False:
        continue
    if order == 'N' or order == 'n':
        info = CreateUser(info)
    elif order == 'E' or order == 'e':
        login(info)
    elif order == 'Q' or order == 'q':
        break

Output results:
|--- New user: N/n ---|
|--- Login account: E/e ---|
|--- Launch procedure: Q/q ---|
|--- Please enter the instruction code:
Please enter instructions:n
 enter one user name:kkk
 Please input a password:123
 Please enter instructions:e
 enter one user name:kkk
 Please input a password:123
 Welcome to xx system
 Please enter instructions:q

Process finished with exit code 0

Built in method of dictionary

fromkeys(...)

It can be seen that dict1 Fromkeys() only creates a new dictionary and has no effect on the original array:
If the value corresponding to the key is given:
But don't expect to give the corresponding values to the keys separately:

>>>dict.fromkeys((1, 2, 3), ('one', 'two', 'three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}

Several methods of accessing dictionary

1.keys(),values(),items()
keys() returns a reference to a dictionary key, values() returns a reference to a dictionary value, and items() returns a reference to a dictionary item
2.get() function
In and not in
If you don't know whether a key is in the dictionary (you can't find a value), you can use the membership operator to judge.
3.clear()
4.copy()
5.pop() and popitem() are both elements in the pop-up dictionary.
6.setdefault(key,str)

a={1: 'one', 2: 'two', 3: 'three', 4: 'four'}
print(a.setdefault(2))
print(a.setdefault(5))
a.setdefault(5, 'five')
a.setdefault(6, 'six')
print(a)
Output results:
two
None
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None, 6: 'six'}

7.update(), update a dictionary with a dictionary or mapping relationship

Topics: Python