Python Dictionary Type Usage example

Source: Internet
Author: User

dictionary ispythonThe unique mapping type in the language, with curly braces{}indicates that a dictionary entry is a key-value pair, and the methodkeys ()returns the list of keys for the dictionary,values ()returns a list of values for the dictionary,items ()returns a list of key-value pairs for the dictionary. There are no restrictions on the values in the dictionary, they can be anypythonobject, but the keys in the dictionary are type-restricted, each key can only correspond to one value, and the key must be a hardy, and all immutable types can be hashed. Immutable CollectionsFrozensetcan be used as a dictionary key, but a mutable collectionSetwill not.


The following are common methods for dictionary types.

Clear () : Deletes all the elements in the dictionary.

copy () : Return Returns a copy of the dictionary (shallow copy).

Fromkeys (seq,val=none) : Create and return a new dictionary to seq val Span style= "Font-family:wenquanyi Micro Hei" > do the initial value corresponding to all the keys in the dictionary.

get (key,default=none) : Returns the keys in the dictionary key value default

Has_key (Key): If the keyKeyexists in the dictionary, returnsTrue, or returnFalse. python2.2after this method is almost obsolete, it is usually usedinchto replace.

items () : Returns a list that contains the tuple of key values in the dictionary.

keys () : Return Returns a list containing the keys in the dictionary.

ITER () : Party Method iteritems () , iterkeys () , itervalues () Same as the non-iterative methods they correspond to, The difference is that they return an iteration instead of a list.

pop (Key[,default]): and Methodsget ()Similarly, if the dictionaryKeykey exists, deleted and returnedDict[key], ifKeykey does not exist, and does not givedefaultthe value that is thrownKeyerrorexception.

Setdefaul T (key,default=none) : And method get () similar if is not present in the dictionary key key, by dict[key]=default

Update (DICT2) : the dictionary Dict2 The key value pair is added to the current dictionary.

values () : Returns a list that contains all the values in the dictionary.


The following is an example of the use of a dictionary using a data system that emulates user logins .

#!/usr/bin/env python db = {} def newuser (): prompt = ' register: ' While true:name = Raw_input (Prompt) if Db.has_key (name  ): prompt = ' name taken, try another: ' Continue else:break pwd = Raw_input (' passwd: ') db[name] = pwd  def olduser (): Name = Raw_input (' login: ') pwd = Raw_input (' passwd: ') passwd = db.get (name) if passwd = = Pwd:print ' login success: ', n  Ame else:print ' login failure ' def showmenu (): prompt = "" "(R) Eister (L) ogin (Q) uit Enter choice:" "" Done = False while Not Done:chosen = False and not chosen:try:choice = Raw_input (Prompt). Strip () [0].lower () except (Eoferror, Keyboardi Nterrupt): choice = ' q ' print ' \nyour choice: [%s] '%choice if choice not in ' RLQ ': print ' invalid option, try again ' else : chosen = true if choice = = ' R ': NewUser () elif choice = = ' L ': olduser () Else:done = true if __name__ = = ' __main__ ': Sho Wmenu ()

the third line of the script initializes an emptyDBDictionary, section9Line throughHas_key ()determine the newly registered user name (the dictionary'sKey) is present, section theline through square brackets[]add a password to a user name (that is, add a value to a key), -Line throughget ()gets the password for the user name (that is, the dictionary'sKeycorresponding to thevalue). Section -Line ofstrip ()is a string-handling function that is used to remove whitespace from the end of a string.



Python Dictionary Type Usage example

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.