Python dictionaries and collections

Source: Internet
Author: User
Tags hashable

1. The dictionary is the only ing type in python. It stores data in the form of key-value pairs. Python performs hash function operations on the key and determines the storage address of the value based on the calculation result. Therefore, the dictionary is unordered and the key must be hashable. It can be hashed to indicate that the key must be of an unchangeable type, such as a number, a string, and a tuples (, 3, 'abc') containing only unchangeable elements '), implement the custom object of the _ hash _ () method (because _ hash _ () must return an integer; otherwise, an exception occurs: TypeError: an integer is required ). You can use hash (obj) to check whether the object is hashable. >>> Class HashEnable (object ):... def _ hash _ (self ):... return 1 >>>> he = HashEnable () >>>> hash (he) 1 >>>> d = {he: 1 }>>>> d = {['1 ', 2]: 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'LIST' 1.1 common dictionary operations (1) create a dictionary >>>> d1 ={}>> d2 = {'player': 'qvod ', 'game ': 'kw '}>>> d1, d2 ({}, {'player': 'qvod', 'game': 'kw '}) >>> d3 = dict (['name', 'Alex '], ['sex ', 'Man']) >>>> d3 {'name': 'Alex ', 'sex': 'man' }>>> d33 = d3.copy () >>> d33 {'name': 'Alex ', 'sex': 'man'} >>> d4 = {}. fromkeys ('Alex ', 'zhou'), 1) >>> d4 {'Alex': 1, 'zhou': 1 }>>> d5 = {}. fromkeys ('Alex ', 'zhou') >>> d5 {'Alex': None, 'zhou': None} (2) traverse the dictionary ps: when you access a non-existent key, a KeyError exception occurs. You can use in or not in to judge before accessing the key. >>> D = {'name': 'alexzhou', 'sex': 'man'} >>> for key in d :... print '% s, % s' % (key, d [key])... name, alexzhou sex, man >>> d ['name'] 'alexzhou '>>> d2 = {'name': 'alexzhou', 'age ': 100 }>>> print 'name: % s, age: % d' % (d2 ['name'], d2 ['age']) name: alexzhou, age: 100 >>> d2 ['sex'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Sex '>>> 'sex' in d2 False >>> 'name' in d2 Tru E (3) Update the dictionary >>> d = {'name': 'alexzhou', 'age ': 100 >>>> d ['age'] = 88 >>> d {'age': 88, 'name': 'alexzhou' >>> d. pop ('age') 88 >>> d {'name': 'alexzhou'} >>> d. clear () >>> d {} 1.2 common built-in functions (1) Comparison of cmp () dictionaries: first, the dictionary size, then the key, last value >>>> d1 = {'abc': 1, 'efg': 2 }>>> d2 = {'abc': 1, 'efg': 2, 'H': 3 }>>> cmp (d1, d2)-1 >>>d3 = {'AB': 1, 'efg ': 2 }>>> cmp (d1, d3) 1 >>> d4 = {'abc': 1, 'efg': 3 }>>> cmp (d1, d4) -1 >>> d5 = {'abc': 1, 'efg': 2 }>> cmp (d1, d5) 0 (2) len () number of return key-value pairs >>>> d = {'abc ': 1, 'efg': 2 }>>> len (d) 2 (3) keys (), values (), items () keys () returns a list Of all keys in the dictionary. values () returns a list Of all values in the dictionary. items () returns a list containing key-value tuples. >>> d = {'name ': 'Alex ', 'sex': 'man'} >>> d. keys () ['name', 'sex'] >>> d. values () ['Alex ', 'man']> d. items () [('name', 'Alex '), ('sex', 'Man')] (4) dict. get (key, default = None) returns the value corresponding to the key in the dictionary. If the key does not exist, default >>> d = {'n' is returned. Ame': 'Alex ', 'sex': 'man'}> d. get ('name', 'not exists') 'Alex '> d. get ('Alex ', 'not exists') 'Not exists' (5) dict. setdefault (key, default = None) if the key exists, it overwrites the previous value. If the key does not exist, add a key-value pair to the dictionary >>> d. setdefault ('name', 'zhou') 'Alex '> d {'name': 'Alex', 'sex ': 'man'} >>> d. setdefault ('hahaha', 'xixi') 'xixi'> d {'hahaha': 'xixi', 'name': 'Alex ', 'sex ': 'man'} (6) dict. update (dict2) adds the dictionary dict2 key-value pairs to dict> d = {'Name': 'Alex ', 'sex': 'man'} >>> d1 = {'age': 100, 'address ': 'shenzhen'} >>> d. update (d1) >>> d {'age': 100, 'address': 'shenzhen ', 'name': 'Alex', 'sex ': 'man' (7) sorted (dict) returns an ordered list of all keys in the dictionary> sorted (d) ['address', 'age', 'name ', 'sex'] 2. set in set python the set object (set) is a group of unordered hash values, which can be set or frozenset ), so set is not hashable. frozenset is hashable and can be used as a dictionary key. >>> S = set ('A') >>> hash (s) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'set'> fs = frozenset ('A')> hash (fs)-1305064881317614714 2.1 Common set Operations (1) create a set> s = set ('alexzhou')> s set (['A', 'E', 'h', 'l', 'O ', 'U', 'x', 'z']) >>> fs = frozenset ('alexzhou') >>> fs frozenset (['A', 'E ', 'H', 'l', 'O', 'U', 'x', 'z']) (2) traverse the set >>> for e in s:... Print e... a e h l o u x z (3) update set (add/update/remove/discard/pop/clear (-=) s. add (obj): add object obj s. update (s1): Use a member in s1 to modify s. s now contains the member s. remove (obj): delete obj from set s. If obj does not exist, the KeyError s is thrown. discard (obj): If obj is a member of s, delete obj s. pop (): delete any object in set s and return s. clear (): delete all elements in set s >>> s = set ('alexzhou') >>> s. update ('hai ') >>> s set (['A', 'E',' I ', 'h', 'l', 'O ', 'U', 'x', 'z']) >>> s. add ('hai ') >>> s set (['A ',' Hai ', 'E',' I ', 'h', 'l', 'O', 'U', 'x', 'z'])> s. remove ('hai ') >>> s set (['A', 'E',' I ', 'h', 'l', 'O ', 'U', 'x', 'z']) >>>> s-= set ('Alex ') >>> s set ([' I ', 'h ', 'o', 'U', 'z']) >>> s. pop () 'I >>> s set (['h', 'z', 'U', 'O']) >>> s. discard ('H') >>> s set (['Z', 'U', 'O']) >>> s. clear () >>> s set ([]) >>> fs = frozenset ('alexzhou') >>> fs. add ('Z') Traceback (most recent call last): File "<stdin>", Line 1, in <module> AttributeError: 'frozenset' object has no attribute 'add' (4) set comparison s1.issubset (s2): checks whether s1 is a subset of s2, if yes, True is returned. Otherwise, False is returned. s1.issuperset (s2): If s1 is a superset of s2, True is returned, otherwise, False is returned. >>> s = set ('alexzhou') >>> fs = frozenset ('alexzhou') >>> s = fs True >>> s2 = set ('alexzhou') >>> s = s2 True >>> s3 = set ('alexzhouj') >>> s> s3 False >>> s <s3 True >>> s (5) union operation (s1 | s2, s1.union (s2) produces Each element of a set must be at least a member of a set. If the Collection types on the left and right sides are the same, the results are the same. If they are different, the results are the same as the left operand. >>> S1 = set ('abc') >>> fs = frozenset ('de') >>> s1 | fs set (['A', 'C ', 'B', 'E', 'D']) >>> type (s1 | fs) <type 'set' >>> type (fs | s1) <type 'frozenset' >>>> s2 = set ('fg') >>> type (s1 | s2) <type 'set' >>>> s1.union (fs) set (['A', 'C', 'B', 'E', 'D']) >>> type (s1.union (fs) <TYPE? Set?> >>> Type (fs. union (s1) <TYPE? Frozenset?> (6) intersection s1 & s2, complementary set s1-s2, exclusive or s1 ^ s2 intersection: elements in the new set are also elements of s1 and s2-> s1.intersection (s2) supplement: elements in the new set only belong to s1, not-> s1.difference (s2) or: elements in the new set cannot belong to both s1 and s2-> s1.1_ric _ difference (s2) >>> fs = frozenset ('de') >>> s = set ('def ') >>> s & fs set (['E', 'D']) >>> s-fs set (['F']) >>> fs-s frozenset ([]) >>> s ^ fs set (['F']) >>> s. intersection (fs) set (['E', 'D']) >>> s. difference (fs) set (['F']) >>> s. symmetric_difference (fs) set (['F'])

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.