Python system learning notes (5) --- dictionary

Source: Internet
Author: User

The dictionary is similar to the address book in which you use the contact name to find the address and contact details. That is, we associate the key (name) and value (details) together. Note that keys must be unique, as if two people happen to have the same name, you cannot find the correct information. Note that you can only use immutable objects (such as strings) as Dictionary keys, but you can use immutable or variable objects as Dictionary values. Basically, you should only use simple objects as keys. Key-value pairs are marked in the dictionary in this way: d = {key1: value1, key2: value2 }. Note that their key/value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly brackets. Remember that key/value pairs in the dictionary have no order. If you want a specific sequence, you should sort them before use. A dictionary is an instance/Object of the dict class. Dictionary: dictionary (map of the C ++ standard library) dict = {'ob1': 'computer ', 'ob2': 'mouse', 'ob3 ': 'printer'} each element is pair, which contains two parts: key and value. Key is of the Integer or string type, and value is of any type. The key is unique, and the dictionary only recognizes the last assigned key value. Key-value pairs are unordered, keys and values can be any objects, and the length can be variable or nested. In the dictionary, sequence operations are not allowed, although the dictionary is similar to the list in some aspects, do not set the list on the dictionary to create 1. directly create: phonebook = {'Alice ': '000000', 'beth': '000000', 'cecil ': '000000'} (keys and values are separated by colons, key-value pairs are separated by commas.) 2. dict functions: >>> items = [('name', 'gumby'), ('age', 42)] # dict first method> d = dict (items) {'age': 42, 'name ': 'gumby' }>>> d = dict (name = 'gumby', age = 42) # second method of dict {'age': 42, 'name ': 'gumby'} >>> d ['*** al'] = 'boys' {'age': 42, 'name': 'gumby ', '*** ual': 'Boys'} * dictionary formatted string * (useful) after the % character in the conversion description, you can add a key enclosed in parentheses, other description elements will be added later. Phonebook = {'Alice ': '000000', 'beth': '000000', 'cecil ': '000000'} print "Alice's phone number is % (Alice) s, Cecil's phone number is % (Cecil) s "% phonebook # % (Alice) s represents the meaning of the output string --> Alice's phone number is 2341, cecil's phone number is 3258 Note: This type of string format is very useful in the template system, string. the Template class is also very useful for such applications. Dictionary Method 1. clear all items in the dictionary: phonebook. clear () # phonebook is a dictionary object 2. copy: only copies the parent object in the dictionary and references the child object. Changing the content of sub-objects affects the copied and replicated dictionaries. Example: x = {'username': 'admin', 'machines ': ['foo', 'bar', 'baz']} y = x. copy () y ['username'] = 'allen 'y ['machines']. remove ('bar') print yprint x output: {'username': 'allen', 'machines ': ['foo ', 'baz']} # y {'username': 'admin', 'machines ': ['foo', 'baz']} # change the value of x linked list sub-objects, the two dictionaries are affected. Apply the sub-object. Deep copy: deepcopy, full copy. Changes to the new dictionary do not affect the original dictionary. From copy import deepcopyd = {'username': 'admin', 'machines ': ['foo', 'bar', 'baz']} dc = deepcopy (d) 3. fromkeys creates a new dictionary using the given key. The default value of each key is None. {}. Fromkey (['name', 'age']) --> {'age': None, 'name': None} dict. fromkey (['name', 'age']) # Call the method directly on dict of all dictionary types --> {'age': None, 'name': None} dict. fromkey (['name', 'age'], '(unknown)') # use None as the default value. You can provide the default value --> {'age': '(unknown )', 'name': '(unknown)'} 4.get get is a more loose Method for accessing dictionary items. In general, an error occurs when you try to access an item that does not exist in the dictionary. But not get. For example, >>> d ={}# empty dictionary >>> print d ['name'] Traceback ........ # error message> print d. get ('name') None # You can customize the default value instead of None, such as d. get ('name', 'n'/A'). Print N/A5.has _ key if there is no name entry to check whether the dictionary contains the given key. D. has_key (k) is equivalent to k in d. Python3.0 does not contain this function. >>> D = {'name': 'fuss '} >>> d. has_key ('age') False >>> d. the has_key ('name') True6.items and iteritems items Methods return all dictionary items in list mode. >>> D = {'name': 'fu', 'age': 24, '*** al': 'boys'} >>> d. items () [('age', 24), ('name', 'fu'), ('*** ual', 'boys')] # The returned iteritems method does not have a special sequence, but will return an iterator object instead of a list: >>> it = d. iteritems () >>> it <dictionary-itemiterator object at 0x011DA580 >>>> list (it) [('age', 24), ('name ', 'fu'), ('*** ual', 'boys')] 7. the keys and iterkeys Methods return keys in the dictionary in the form of a list, while the iterkeys method returns the iterator for the key. >>> D. keys () ['age', 'name', '*** ual'] 8.pop is used to obtain the value corresponding to the given key, then, remove the key-value pair from the dictionary. >>> D = {'X': 1, 'y': 2 }>>> d. pop ('x') 1 >>> d {'y': 2} 9. the popitem method is similar to list. pop, the latter will pop up the last element of the list. However, popitem pops up a random item, indicating that the dictionary does not have the "last element" or other concepts related to order. >>> D = {'X': 1, 'y': 2 }>>> d. popitem () ('x': 1) # random 10. to some extent, the setdefault method is similar to the get method, that is, it can obtain the value associated with the given key. In addition, setdefault can also set the corresponding key value if the dictionary does not contain a given key. >>> D ={}>> d. setdefault ('name', 'n'/A') 'n'/A'> d {'name ': 'N'/A' }>>> d ['name'] = 'allen '>>> d. setdefault ('name', 'n'/A') 'allen '> d {'name': 'allen'} 11. the update method can use one dictionary item to update another dictionary: >>> d = {'X': 123, 'y ': 456 >>>> B = {'X': 789 }>>> d. update (B) >>> d {'X': 789, 'y': 456} provides dictionary items to be added to the old dictionary, if the same key exists, it will be overwritten. 12. Return the dictionary value in the form of a list of values and itervalues values methods (itervalues returned value iterator ). For example, d = {'name': 'fu', 'age': 24, '*** ual': 'boys'} print d. keys () # Return the dictionary Key List print d. values () # Return the dictionary Value List ['age', 'name', '*** ual'] # key list ['fu', 24, 'boys'] # Value List [python] #-*-coding: cp936-*-params = {"server": "mpilgrim", "database": "master ", "uid": "sa", "pwd": "secret"} print params. keys () print params. values () print params. items () print [k for k, v in params. items ()] print [v for k, v in params. it EMS ()] print ["% s = % s" % (k, v) for k, v in params. items ()] print params. has_key ("server") print params. get ("server") params ["pwd"] = "hello pwd" print params. items () params ["hello list"] = [1, 2, 3, 4] print params del params ["hello list"] print params # print params. popitem () # traverse for key in params. keys (): print key, '\ t', params [key] # join print ";". join (["% s = % s" % (k, v * 2) for k, v in params. items ()] Use a dictionary to implement simple switch statements. (It was written in section 1) [python] from _ future _ import division x = 1 y = 2 operator = "/" result = {"+ ": x + y, "-": x-y, "*": x * y, "/": x/y} print result. get (operator) exercises invert keys and values in the dictionary. Use one dictionary as the input, output the other dictionary, and use the former key as the value, and the former value as the key. However, if the values are the same, the first d = {'abc': 1, 'def ': 2, 'ghi': 3, 'jkl': 3} = "{1: 'abc', 2: 'def ', 3: 'ghi '}

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.