Dictionary of Python syntax

Source: Internet
Author: User

* Feature: unordered, the only built-in ing type. Hash Tables or associated arrays. Key is unique. You can use objects of fixed length. You cannot use lists, dictionaries, or tuples that contain variable length types. Access Mode: m [k], and k is the key. If no value is found, the system reports the KeyError. Definition: dict (one = 1, two = 2) Note that the strings one and two have no quotation marks. Dict ({'one': 1, 'two': 2}) dict (zip ('one', 'two'), (1, 2 ))) dict ([['two', 2], ['one', 1]) methods and operations are as follows: Project function len (m) return the number of items in the dictionary d. d [key] Return the item of d with key. raises a KeyError if key is not in the map. the subclass of dict can define _ missing _ () to change this point. Application: collections. defaultdict. d [key] = valueSet d [key] to value. del d [key] Remove d [key] from d. raises a KeyError if key is not in the map. key in dReturn True if d has a key, else False. key not in dEquivalent to not key in d. iter (d) Return an iterator over the keys of the dictionary. this is a shortcut cut for iterkeys () d. clear () Remove all items from the dictionary. d. copy () Return a shallow copy of th E dictionaryd. fromkeys (seq [, value]) creates and returns a new dictionary, which uses the elements in seq as the dictionary key, val is the initial value corresponding to all keys in the dictionary (if this value is not provided, the default value is None ). class method. D. get (key [, default]) Return the value for key if key is in the dictionary, else default. if default is not given, it defaults to None, so that this method never raises a KeyError. d. has_key (key) is not recommended for d. items () Return a copy of the dictionary's list of (key, value) pairs. d. iteritems () Return an iterator over the dictionary's (key, value) pairs. see the note for dict. items (). d. iterkeys () Return an ite Rator over the dictionary's keys. d. itervalues () Return an iterator over the dictionary's values. d. keys () Return a copy of the dictionary's list of keys. d. pop (key [, default]) If key is in the dictionary, remove it and return its value, else return default. if default is not given and key is not in the dictionary, a KeyError is raised. d. popitem () Remove and return an arbitrary (key, value) pair fro M the dictionary. d. setdefault (key [, default]) If key is in the dictionary, return its value. if not, insert key with a value of default and return default. default ults to None. d. update (B) Update the dictionary with the key/value pairs from other, overwriting existing keys. return None. update () accepts either another dictionary object or an iterable of key/value pairs (as tuples or other IIRs Bles of length two ). if keyword arguments are specified, the dictionary is then updated with those key/value pairs: d. update (red = 1, blue = 2 ). d. values () Return a copy of the dictionary's list of values. d. viewitems () Return a new view of the dictionary's items (key, value) pairs ). d. viewkeys () Return a new view of the dictionary's keys d. viewkeys () Return a new view of the dictionary's values. see Fromkeys () is a class method. Items (), keys (), values () returns the list (Python2), and Python 3 returns the iterator. The conversion result is as follows: items = list (m. items (). the View object returns a dictionary dynamic View. It supports length, iteration, and relationship: len (dictview) Return the number of entries in the dictionary. iter (dictview) Return an iterator over the keys, values or items (represented as tuples of (key, value) in thedictionary. xin dictview Return Trueif x is in the underlying dictionary's keys, values or items (in thelatter case, x shocould be a (key, value) tuple ). set Operations are also supported: dictview & otherdictview | otherdictview-otherdictview ^ Other has different elements. # PythonPython2.7.3 (default, Jan 5 2013, 11:24:11) [GCC 4.4.620120305 (Red Hat 4.4.6-4)] on linux2Type "help", "copyright ", "credits" or "license" for more information. >>> dishes = {'eggs ': 2, 'sausage': 1, 'bacon': 1, 'spam': 500 }>>> keys = dishes. viewkeys () >>> keysdict_keys (['eggs ', 'bacon', 'sausage', 'spam']) >>> values = dishes. viewvalues () >>> valuesdict_values ([1,500,]) >>> n = 0 >>> for val in valu Es :... n + = val... >>> print (n) 504 >>> list (keys) ['egg', 'bacon ', 'sausage', 'spam'] >>> list (values) [2, 1, 1,500] >>> del dishes ['eggs '] >>> del dishes ['sausage'] >>>> list (keys) ['bacon ', 'Spam'] >>> keys & {'egg', 'bacon', 'salad'} set (['bacon']) * dictionary Construction Example: phonebook = {'Alice ': '000000', 'beth': '000000', 'cecil ': '000000'} stock = {"name": "GOOG ", "shares": 100, "price": 490.10} name = stock ["name"] value = stock ["shares "] * Shares [" price "] special attention should be given to the quotation marks in brackets when the string type is used. Prices ={}# Anempty dictprices = dict () # An empty dictd = {} d [, 3] = "foo" d [(, 3)] = "foo" d [, 3] = "bar" d [(, 3)] = "bar" use in to judge the membership relationship: if "SCOX" in prices: p = prices ["SCOX"] else: p = 0.0 simpler method: p = prices. get ("SCOX", 0.0) to get the key list: syms = list (prices) >>> syms ['goog', 'aap', 'ibm ', 'msft '] delete an element: del prices ["MSFT"] function Dict can build a dictionary from other mappings or sequences >>> items = [('name', 'gumby '), ('age', 42)] >>> d = dict (items) >>> D {'age': 42, 'name ': you can also use the parameter method:> d = dict (name = 'gumby ', age = 42) >>> d {'age': 42, 'name': 'gumby'} Initialize an empty dictionary: >>> x ={}>>> x [42] = 'foobar' >>>> x {42: 'foobar'} * formatted output: >>> phonebook {'beth ': '20140901', 'Alice ': '20160901', 'cecil': '20160901' }>>> "Cecil's phone numberis % (Cecil) s. "% phonebook" Cecil's phone number is 3258. ">>> template = '''

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.