Daydayup_python self-study record [5]_dict and set learning

Source: Internet
Author: User

What is Dict

We already know that list and tuple can be used to represent sequential collections, for example, the name of the class:

[' Adam ', ' Lisa ', ' Bart ']
Or the test results list:

[95, 85, 59]
However, to find the corresponding score according to the name, it is inconvenient to use two list to indicate.

If you associate a name with a score, make a similar look-up table:

' Adam ' ==> 95
' Lisa ' ==> 85
' Bart ' ==> 59
Given a name, you can find the score directly.

Python's dict is dedicated to doing this. The lookup table for "name"-"score" is shown in Dict as follows:

d = {    ‘Adam‘95,    ‘Lisa‘85,    ‘Bart‘59}

We call the name key, and the corresponding result, called Value,dict, is to find value by key.

The curly braces {} indicate that this is a dict, and then follow the Key:value and write them out. The last comma of a key:value can be omitted.

Since Dict is also a collection, the Len () function can calculate the size of any collection:

>>> len(d)3

Note: A key-value is counted one, so the dict size is 3.

Visit dict

We have been able to create a dict that represents the correspondence between the name and the score:

D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59
}
So, how to find the corresponding score according to the name?

You can simply use the form of D[key] to find the corresponding value, which is like the list, but the list must return the corresponding element using the index, and Dict uses key:

>>> print d[‘Adam‘]95>>> print d[‘Paul‘]Traceback (most recent call last):  File "index.py", line 11, in <module>    print d[‘Paul‘]KeyError: ‘Paul‘

Note: The value of dict is accessed by key, and Dict returns the corresponding value as long as the key exists. If key does not exist, it will directly error: Keyerror.

There are two ways to avoid keyerror:

First, determine whether the key exists, with the in operator:

if ‘Paul‘ in d:    print d[‘Paul‘]

If ' Paul ' is not present, the IF statement evaluates to False, and the print d[' Paul ' is not executed naturally, thus avoiding the error.

The second is to use the dict itself to provide a get method, when the key does not exist, return to none:

>>> print d.get(‘Bart‘)59>>> print d.get(‘Paul‘)None
Features of Dict

The first feature of Dict is that the search speed is fast, regardless of whether the dict has 10 elements or 100,000 elements, the search speed is the same. The search speed of the list decreases as the element increases.

However, dict search speed is not without cost, dict the disadvantage is that the memory is large, but also waste a lot of content, the list is just the opposite, the memory is small, but the search speed is slow.

Because Dict is located by key, in a dict, key cannot be duplicated.

The second feature of Dict is that the stored key-value sequence pair is not in order! This is not the same as list:

D = {
' Adam ': 95,
' Lisa ': 85,
' Bart ': 59
}
When we try to print this dict:

>>> print d{‘Lisa‘: 85, ‘Adam‘: 95, ‘Bart‘: 59}

The order of printing is not necessarily the order in which we are created, and the order in which different machines are printed may be different, which means that the dict interior is unordered and cannot be stored in an ordered collection with Dict.

The third feature of Dict is that elements that are key must be immutable, and the basic types of python, such as strings, integers, and floating-point numbers, are immutable and can be used as keys. But the list is mutable and cannot be a key.

What errors will be reported when trying to try list as key.

Immutable this limit is only used for key,value whether the variable does not matter:

{    ‘123‘: [1, 2, 3],  # key 是 str,value是list    123: ‘123‘,  # key 是 int,value 是 str    (‘a‘, ‘b‘): True  # key 是 tuple,并且tuple的每个元素都是不可变对象,value是 boolean}

The most commonly used key is also a string, because it is most convenient to use.

Update Dict

Dict is mutable, meaning that we can add new Key-value to dict at any time. For example, there are dict:
To add a new classmate ' Laihua ' score of 72, use the assignment statement:

>>> d[‘laihua‘] = 72

Then look at the contents of Dict:

>>> print d {‘Lisa‘: 85, ‘laihua‘: 72, ‘Adam‘: 95, ‘Bart‘: 59}

If the key already exists, the assignment replaces the original value with the new value:

>>> d[‘Bart‘] = 60>>> print d{‘Lisa‘: 85, ‘Paul‘: 72, ‘Adam‘: 95, ‘Bart‘: 60}
Delete a dictionary element

The ability to delete a single element also clears the dictionary, emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:

#!/usr/bin/python# -*- coding: UTF-8 -*-dict = {‘Name‘: ‘Zara‘, ‘Age‘: 7, ‘Class‘: ‘First‘};del dict[‘Name‘]; # 删除键是‘Name‘的条目dict.clear();     # 清空词典所有条目del dict ;        # 删除词典print "dict[‘Age‘]: ", dict[‘Age‘];print "dict[‘School‘]: ", dict[‘School‘];

However, this throws an exception because the dictionary no longer exists after Del:

dict[‘Age‘]:Traceback (most recent call last):  File "test.py", line 8, in <module>    print "dict[‘Age‘]: ", dict[‘Age‘];TypeError: ‘type‘ object is unsubscriptable

Note: The Del () method is also discussed later.

Traverse Dict

Since Dict is also a collection, traversing the dict is similar to traversing the list and can be implemented through a for loop.

Use the For loop directly to traverse the Dict key:

# 遍历dictfor key in grade:  print key + ‘:‘, grade[key]

Because the corresponding value can be obtained by key, the value can be obtained in the loop body.

Dict built-in functions & methods

The Python dictionary contains a

1   cmp(dict1, dict2)比较两个字典元素。(相同返回0,不同返回1)2   len(dict)计算字典元素个数,即键的总数。3   str(dict)输出字典可打印的字符串表示。4   type(variable)返回输入的变量类型,如果变量是字典就返回字典类型。

The Python dictionary contains the following built-in methods:

1   radiansdict.clear()删除字典内所有元素2   radiansdict.copy()返回一个字典的浅复制3   radiansdict.fromkeys()创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值4   radiansdict.get(key, default=None)返回指定键的值,如果值不在字典中返回default值5   radiansdict.has_key(key)如果键在字典dict里返回true,否则返回false6   radiansdict.items()以列表返回可遍历的(键, 值) 元组数组7   radiansdict.keys()以列表返回一个字典所有的键8   radiansdict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default9   radiansdict.update(dict2)把字典dict2的键/值对更新到dict里10  radiansdict.values()以列表返回字典中的所有值
Set

The role of Dict is to establish a set of keys and a set of value mappings, Dict key cannot be duplicated.

Sometimes, we just want to dict key, do not care about the value of key corresponding to the purpose is to ensure that the elements of this set will not be duplicated, then the set will come in handy.

The set holds a series of elements, which are similar to the list, but the set elements are not duplicates and are unordered, which is similar to the Dict key.

The way to create a set is to call set () and pass in a list,list element as the set element:

>>> s = set([‘A‘, ‘B‘, ‘C‘])

You can view the contents of the set:

>>> print sset([‘A‘, ‘C‘, ‘B‘])

Note that the above print form is similar to list, but it is not a list, and it can be seen that the order of printing and the order of the original list may be different because the elements stored inside the set are unordered.

Because set cannot contain duplicate elements, what happens when we pass in a list that contains repeating elements?

>>> s = set([‘A‘, ‘B‘, ‘C‘, ‘C‘])>>> print sset([‘A‘, ‘C‘, ‘B‘])>>> len(s)3

The result shows that the set automatically removes the duplicate elements, the original list has 4 elements, but the set has only 3 elements.

Access Set

Because set stores unordered collections, we cannot access them through an index.

Accessing an element in a set actually determines whether an element is in the set.

For example, a set that stores the name of a class student:

>>> s = set([‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘])

We can use the in operator to judge:

Is Bart a classmate of the class?

>>> ‘Bart‘ in sTrue

Is bill a classmate of the class?

>>> ‘Bill‘ in sFalse

Is Bart a classmate of the class?

nameL=[‘ll‘,‘aa‘,‘bb‘,‘cc‘]nameS=set(nameL)if ‘AA‘ in nameS:  print ‘true‘else:  print ‘false‘if ‘aa‘ in nameS:  print ‘true‘else:  print ‘false‘

It appears that the capitalization is important, ' Bart ' and ' Bart ' are considered to be two different elements

Features of Set

The internal structure of set is much like the dict, the only difference is that it does not store value, so it is very fast to determine whether an element is in set.

The set stored element is similar to the Dict key, and must be an immutable object, so any mutable object cannot be placed in the set.

Finally, the set stores the elements that are not in order.

Where can these features of set be applied?

Monday to Sunday you can use the string ' MON ', ' TUE ', ... ' SUN ' said.

Suppose we let the user enter a day from Monday to Sunday, how to tell if the user's input is a valid week?

Can be judged with an if statement, but this is tedious:

x = '??? ' # user-entered string

if x!= ‘MON‘ and x!= ‘TUE‘ and x!= ‘WED‘ ... and x!= ‘SUN‘:    print ‘input error‘else:    print ‘input ok‘

Note: In the IF statement ... Indicates that no other week names are listed, when testing, enter complete.

If you create good one set beforehand, include ' MON ' ~ ' SUN ':

weekdays = set([‘MON‘, ‘TUE‘, ‘WED‘, ‘THU‘, ‘FRI‘, ‘SAT‘, ‘SUN‘])

To determine if the input is valid, just determine if the string is in set:

x = '??? ' # user-entered string

if x in weekdays:    print ‘input ok‘else:    print ‘input error‘

In this way, the code is much simpler.

Traversing set

Because set is also a collection, traversing set is similar to traversing a list and can be implemented through a for loop.

You can iterate through the elements of a set directly using a For loop:

>>> s = set([‘Adam‘, ‘Lisa‘, ‘Bart‘])>>> for name in s:...     print name... LisaAdamBart

Note: When observing A For loop, the order of the elements and the order of the list is likely to be different when traversing set, and the results of running on different machines may be different.

Update set

Because set stores a set of unordered elements that are not duplicated, the update set mainly does two things:

One is to add the new element to the set, and the other is to remove the existing element from the set.

When adding an element, use the Add () method of Set:

>>> s = set([1, 2, 3])>>> s.add(4)>>> print sset([1, 2, 3, 4])

If the added element already exists in set, add () will not error, but will not be added:

>>> s = set([1, 2, 3])>>> s.add(3)>>> print sset([1, 2, 3])

When removing elements from a set, use the Remove () method of Set:

>>> s = set([1, 2, 3, 4])>>> s.remove(4)>>> print sset([1, 2, 3])

If the deleted element does not exist in the set, remove () will error:

>>> s = set([1, 2, 3])>>> s.remove(4)Traceback (most recent call last):  File "<stdin>", line 1, in <module>KeyError: 4

So with Add () can be added directly, and remove () before you need to judge.

Personal Practice Code (Basic)

#!/usr/bin/python#-*-Coding:utf-8-*-Grade = {' Adam ': the,' Lisa ': -,' Bart ': -}PrintLen (grade);Printgrade[' Adam '];if ' Paul ' inchGradePrintgrade[' Paul ']if ' Lisa ' inchGradePrintgrade[' Lisa ']# Get Method#为空的时候PrintGrade.get (' Bart ')PrintGrade.get (' Laihua ') grade[' Laihua ']= thePrintgradegrade[' Adam ']= AboutPrintGrade# Traverse Dict forKeyinchGradePrintKey +': ', Grade[key]# Setl1=[' A ',' B ',' C ']s1=set (L1)PrintS1#list Pure when repeating valuesl2=[' A ',' B ',' C ',' B ']s2=set (L2)Prints2namel=[' ll ',' AA ',' BB ',' CC ']names=set (Namel)if ' AA ' inchNameS:Print ' true 'Else:Print ' false 'if ' AA ' inchNameS:Print ' true 'Else:Print ' false 'Weekdays = Set ([' MON ',' TUE ',' WED ',' THU ',' FRI ',' SAT ',' SUN ']) Input=raw_input ("Please input some day:")ifInputinchWeekdays:Print "OK"Else:Print "Error"s = Set ([1,2,3]) forIinchRange (3,6):ifIinchS:s.remove (i)Else:Print ' ERROR ', I

Daydayup_python self-study record [5]_dict and set learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.