day05 dictionary

day05 dictionary

Today Executive Summary

  1. Dictionary - is very important
  2. Dictionary nesting

Yesterday Recap

  1. List

    1. List for storing large amounts of data, the keyword list is
    2. The list is variable and orderly (available positioning index lookup), can be iterative
    • Increase the list (append, insert, extend)
    • Delete List (remove, pop, clear, del)
    • Modifying the list (LST [index] = value, can be sliced)
    • Find a list (index, for circulation)
  2. Tuple

    1. Tuple is an immutable list of keywords is tuple
    2. Tuples ordered, immutable, may iterate
  3. range

    1. A digital loop, the iteration
    2. Python 2 returns the list, return the range itself Python 3
    3. range (start position: end position: step) care regardless Ding
    4. range (end position)

Today's detailed content

dictionary

We have a look at the following example:

name_lst = ["新力", "一帆", "海绵", "秀"]
id_lst = [18, 9, 25, 50]

Among them, the list name_lstis stored in a classmate's name, id_lststored in the corresponding number of school students. For example, 新力school number is 18.

If we want to find Sony's school, going to another school number found in the list corresponds to the value of its index, for example:

name_lst[0]
id_lst[0]

Although such operations to meet our needs, but apparently somewhat cumbersome. And once any of a list of index changes (such as the insertion or deletion of data carried out the operation), it is necessary to perform the same changes to other list, otherwise it will cause confusion.

If we use a dictionary to carry out this type of operation, you can avoid such trouble.

Dictionary is one of the basic data types in Python. Dictionary {} is the only use, containing key-value pairs of data types. Data dictionary is a key-value pairs.

Dictionary key in Python isdict

Dictionary for storing large amounts of data, a larger amount of data stored in the list.

The dictionary is possible association between the data and the data.

The dictionary definition method looks like this: dic = {'键': '值'}specific example is:

dic = {"新力": ["开车", "唱", "跳"], "一帆": 9, 25: "海绵", True: "秀", (1, 2, 3): "大圣"}

The corresponding values ​​can be found accurately by a bond:

print(dic["新力"])

Add here a concept 哈希:

  • Variable data type is not hashed
  • Data Types hash immutable

Currently we have learned variable data types: lists and dictionaries; immutable data types: integer, string, boolean and tuples.

Dictionary keys must be immutable data type (i.e. hashable) and unique (dictionary keys can only be one). If the dictionary appears duplicate key, behind the key to overwrite the previous pairs.

Dictionary values ​​may be any type of data.

Dictionary is itself a variable data types:

dic = {{'a': 1}: 'alex'}
print(dic)

Traceback (most recent call last):
  File "C:/Users/Sure/PyProject/day05/01 exercise.py", line 54, in <module>
    dic = {{'a': 1}: 'alex'}
TypeError: unhashable type: 'dict'

Run the above code will be given the wrong because the dictionary is not a hash of the data type. In other words, the dictionary is variable.

Increase of dictionary elements

Dictionary of operation can be increased by dic["键"] = "值"way of implementation:

dic = {"key": 1}
dic["alex"] = 89
print(dic)

输出的内容为:{'key': 1, 'alex': 89}

This increase in variable assignment by the method of approach is somewhat "violent" because if the dictionary that exist in the same key, the assignment will replace the original key value corresponding to the new value:

dic = {'key': 1, 'alex': 18}
dic["alex"] = 89
print(dic)

输出的内容为:{'key': 1, 'alex': 89}

There is also a relatively "soft" elements increases dictionary method .setdefault(). In this way, if the original dictionary have the same key, the return value is changed corresponding to the key value, the operation is not modified. If this value does not exist in the original dictionary, it will add new pairs. The default value is None, you can also customize the value to be added. After the new value corresponding to the key range is increased. E.g:

dic = {'key': 1}
print(dic.setdefault('key'))
print(dic.setdefault('meet'))
print(dic.setdefault('alex', 89))
print(dic)

输出的结果为:
1
None
89
{'key': 1, 'meet': None, 'alex': 89}

For .setdefault()the return value, you can remember this: the key corresponding to the value of the final dictionary of what is and what is returned.

Dictionary setdefault method

.setdefault()The method is carried out by two steps:

  1. First by subtracting the dictionary lookup, if the key exists, it returns the corresponding value will not continue with the second step; if the key does not exist, the return value will be assigned to the key, by default None, to perform the second step.
  2. Add keys and values ​​to the dictionary

Delete dictionary

Delete the main dictionary .clear(), .pop(), .popitem()and delfour methods.

.clear()The method used to empty dictionary, the use of this method will be an empty dictionary:

dic = {'key': 1, 'dsb': 'alex'}
dic.clear()    # 字典是可变数据类型,可以直接用方法来修改,不必重新赋值
print(dic)

输出的结果为:{}

.pop()The method requires the input key to be deleted as a parameter and returns the deleted key value corresponding to:

dic = {'key': 1, 'dsb': 'alex'}
print(dic.pop('key'))

.popitem()It is randomly deleted. But in Python 3 and the latest version of Python 2, the default dictionary to delete the last key-value pair, the return value is the key to delete the tuple (note that a tuple, rather than .pop()the same value is put back ):

dic = {'key': 1, 'dsb': 'alex'}
print(dic.popitem())

输出的结果为:('dsb', 'alex')

And a list of different is not in the dictionary removemethod.

The dictionary delusage and a list of methods are very similar, if not specify the key to be deleted, it will delete the entire dictionary:

dic = {'key': 1, 'dsb': 'alex'}
del dic
print(dic)

Traceback (most recent call last):
  File "C:/Users/Sure/PyProject/day05/01 exercise.py", line 80, in <module>
    print(dic)
NameError: name 'dic' is not defined

After the code runs error, because dic has been completely removed.

We can also specify the key way to delete a specific key-value pairs:

dic = {'key': 1, 'dsb': 'alex'}
del dic['dsb']
print(dic)

输出的结果是:{'key': 1}

Dictionary changes

There are two forms of modified dictionary, the first force is increased with a method dic['键'] = '值'for the modification key already exists; the second is by .update()merging two dictionary methods.

Used dic['键'] = '值'to modify, when the specified key exists in the dictionary, corresponding to the key value will be replaced with the new values:

dic = {"key":1,"dsb":"alex"}
dic["dsb"] = "Alex"  # 修改
dic["ss"] = "Alex"   # 增加
print(dic)

输出的结果为:{'key': 1, 'dsb': 'Alex', 'ss': 'Alex'}

.update()Ways to merge two dictionaries. updateLevel input dictionary is higher than the previous dictionary. That is, if the new input key already exists in the dictionary on the key corresponding to the new value will replace the old values:

dic = {'key': 1, 'dsb':'alex'}
dic.update({'key': 2, 'meet': 23})
print(dic)

输出的结果为:{'key': 2, 'dsb': 'alex', 'meet': 23}

Dictionary lookup

Dictionary can be directly referred to by their key values, but this way is relatively Find "violence": When there is key, returns the corresponding value; when the key is not present, the program will complain:

dic = {'key': 1, 'dsb': 'alex'}
print(dic['dsb'])   # 返回'dsb'
print(dic['alex'])  # 程序报错

Because of this direct method to find the key when there is no will complain, sometimes we need to use the .get()method: When there is key, back key the corresponding value; when the key does not exist, returns None:

dic = {'key': 1, 'dsb': 'alex'}
print(dic['dsb'])   # 返回'dsb'
print(dic['alex'])  # 返回None

We can even change the key to return value does not exist:

print(dic.get("alex","没有找到啊"))

We can also .keys(), .values()and .items()method for acquiring all of the dictionary keys, values, and pairs. The return value is a kind of these three methods 高仿列表, but can not support the iterative index. We can return to the list of high imitation into common list by list function:

dic = {'key': 1, 'dsb': 'alex'}
print(dic.keys())
print(dic.values())
print(dic.items())
for i in dic.keys():
    print(i)
print(list(dic.values()))

You can also use a for loop iterations dictionary, it will traverse the dictionary keys:

dic = {'key': 1, 'dsb': 'alex'}
for i in dic:
    print(i)

Deconstruction

We just mentioned the dictionary .items()method returns a list of tuples of key-value pairs key tuples:

dic = {'key': 1, 'dsb': 'alex'}
print(dic.items())

输出的内容为:dict_items([('key', 1), ('dsb', 'alex')])

We get a list of key-value pairs, each key-value pairs in the form of tuples.

If now, we need to extract every element of them, you can do this:

dic = {'key': 1, 'dsb': 'alex'}
lst = list(dic.items())
print(lst[0][0])
print(lst[0][1])
print(lst[1][0])
print(lst[1][1])

Although possible, but very cumbersome, we need to use this method of construction.

The basic style structure is as follows:

a, b = (10, 20)
print(a)
print(b)

As can be seen, 10and 20a value is assigned to each aand b. This method of data respectively assigned to the right of the equal sign in front of the equal sign variable, deconstruction.

Look at the following examples:

a, b = '你好'
print(a)
print(b)

aGet to , bget to . In other words, the structure is not only applicable to tuples, also applies to the strings. In fact, as long as the iterable objects, it can be used to deconstruct:

a,b,c = [10,20,30]
print(a)
print(b)
print(c)

a,b = {"key":1,"key2":2}
print(a)
print(b)

Note that, when the dictionary during the iterations, it will only return key, but does not return a value.

When the structure, the number of variables to the equation on the left and right of the equal number of elements, otherwise it will error.

If you want to use a small number of variables to receive more of the elements, we need *to be more elements of the final surface will be 聚合:

a, b, *c = (1, 2, 3, 4, 5, 6)
print(a)
print(b)
print(c)

输出的结果是:
1
2
[3, 4, 5, 6]

3, 4, 5And 6are unified 打包to the c, 打包after the data is 列表stored in the form.

Return to the previous dictionary .items()method returns the value of the use, if the method of the structure, we can easily print out the contents of key-value pairs to:

dic = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4}
for k, v in dic.items():
    print(k, v)
    
输出的内容为:
key1 1
key2 2
key3 3
key4 4

Dictionary nesting

There is such a dictionary below:

house = {
    101:{1:{"皮裤男":{"某女":["小钢炮"],"国际章":["熊大","熊二"]},
            2:{"林俊杰":["磨牙"]}}},
    102:{1:{"皮裤女":{"林宥嘉":["说谎","你是我的眼"]}},
         2:{"王菲":["天后","传奇","红豆","笑忘书"]}},
    103:{1:{"韦小宝":{"阿珂":"刺客","建宁":"公主","双儿":"丫鬟","教主老婆":"龙儿"}},
         2:{"张无忌":{"灭绝师太":"倚天剑","金毛狮王":"屠龙刀","张三丰":"太极拳"}}},
    104:{1:{"西游记":{"大圣":"金箍撸撸棒","唐僧":"叨逼叨","八戒":"高老庄主任"}}},
    105:{1:{"水浒传":{"武松":"打老虎","鲁智笙":"拔树","林冲":"教头","宋江":"老大"}},
         2:{"官场":{"高俅":"足球"}}},
    106:{1:{"老男孩":{"alex":"dsb","wusir":"污","宝元":"大卡车","江毅":"兽"}}},
}

To find which of "倚天剑"the word and "熊大"the word, we can find:

print(house[103][2]['张无忌']['灭绝师太'][2])
print(house[101][1]['皮裤男']['国际章'][0][0])

From the example above, we can see that the dictionary is compared to the list of great advantage:

  1. Find what is more convenient dictionary
  2. Dictionary lookup faster

Dictionary can also simplify the process of flow control.

For example, if we need to design such a program, the user input number, the program automatically returns corresponding to the number of dishes. If we use the conditional sentence if implemented would be very tedious:

while True:
    choose = int(input("请输入数字(1-12):"))
    if choose == 1:
        print('饺子')
    elif choose == 2:
        print('粥')
    elif choose == 3:
        print('面条')
    elif choose == 4:
        print('肉')
    elif choose == 5:
        print('土')
    elif choose == 6:
        print('东南风')
    elif choose == 7:
        print('切糕')
    elif choose == 8:
        print('烤全羊')
    elif choose == 9:
        print('烤骆驼')
    elif choose == 10:
        print('锅包肉')
    elif choose == 11:
        print('杀猪菜')
    elif choose == 12:
        print('乱炖')
    else:
        print('输入错误,请重新输入!')

If we use the dictionary approach, just so you can:

dic = {"1":"饺子",
       "2":"粥",
       "3":"面条",
       "4":"肉",
       "5":"土",
       "6":"东南风",
       "7":"切糕",
       "8":"烤全羊",
       "9":"烤骆驼",
       "10":"锅包肉",
       "11":"杀猪菜",
       "12":"乱炖"
       }
while True:
    choose = input("请输入数字(1-12):")
    if choose in dic:
        print(dic[choose])
    else:
        print('输入错误,请重新输入!')

We see, then use a dictionary, saving a lot of code, but also a lot less code duplication. If you later need to increase or deletion list, only need to operate in a dictionary, you do not need to make changes to the program, post-maintenance and more convenient.

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/11514521.html