Python Basic Learning (Dictionary object, set object)

Source: Internet
Author: User

1.dict Dictionary Objects

A. Defining objects

D={' a ': +, ' B ': 12}
B. Get value d[' a ' by key

Method 1.
Determine if key exists
If ' a ' in D:
D[' a ']
Method 2: Return the None data by using the Get method if it does not exist
D.get (' a ');


Dict Find Fast list slows down as the number of elements increases
Dict consumes a lot of memory to consume a large amount of content list memory small find slow
Key in Dict cannot be repeated dict no order

Dict key is not changeable string integer floating point number is immutable can do key but list variable so list can not be used as key


' 123 ': [A]
123: ' 123 '
(' A ', ' B '): True

C. dict adding new elements
d[' Paul ']=72 overwrite the value in the original key if it can exist


D. Traverse dict to traverse key with a for loop
D={' a ': +, ' B ': 55}
For key in D
Print key
Print D[key]
Print key+ ': ', +d[key]
------------------------------------------------
2.set objects

Set does not repeat unordered

A. Defining objects
S=set ([' A ', ' B ', ' C '])

Len (s) Gets the length of s

An unordered collection is an element that cannot be accessed by an index to access the set, or whether the element is in set

' Bar ' in
Set Case sensitive

The difference between set and dict is that there is no value to determine if the element is in set quickly
The set element is an immutable element

B. Traversing a set object set is also a set for loop implementation

S=set ([' A ', ' B '])
For name in S
Print S

C. Update set add Element ()
S.add (4);

D. Delete element S.remove (3); If the element does not exist, the deletion is an error and must be judged beforehand

S=set ([' A ', ' B '])
L=[' A ', ' B ', ' C ', ' d ']
For name in L:
If name in S
S.remove (name);
Else
S.add (name);

Python Basic Learning (Dictionary object, set object)

Related Article

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.