Python dictionary type usage example

Source: Internet
Author: User

Python dictionary type usage example

DictionaryIt is the only ing type in python. It is represented by braces {}. A dictionary entry is a key-value pair. The method keys () returns the dictionary Key List, values () returns the list of dictionary values. items () returns the list of dictionary key-value pairs. There are no restrictions on the values in the dictionary. They can be any python object, but the keys in the dictionary have type restrictions. Each key can only correspond to one value, and the keys must be ha-compatible, all unchangeable types are hashable. The frozenset element of an unchangeable set can be used as the dictionary key, but the variable set cannot.

 

The following are common dictionary types:Method.

Clear (): Delete all elements in the dictionary.

Copy (): Returns a copy of the Dictionary (Shortest copy.

Fromkeys (seq, val = None): Create and return a new dictionary. Use the elements in seq as the keys of the dictionary, and val as the initial values corresponding to all keys in the dictionary.

Get (key, default = None): Return the value corresponding to the key in the dictionary. If the key does not exist in the dictionary, the default value is returned.

Has_key (key): If a key exists in the dictionary, True is returned; otherwise, False is returned. After python2.2, this method is almost obsolete and usually replaced by in.

Items (): Returns a list of key-value pairs in the dictionary.

Keys (): Returns a list of dictionary types.

Iter (): Methods iteritems (), iterkeys (), and itervalues () are the same as their non-iterative methods. The difference is that they return an iterator instead of a list.

Pop (key [, default]): Similar to the get () method, if the key in the dictionary exists, delete and return the dict [key]. If the key does not exist and the default value is not given, a KeyError exception is thrown.

Setdefault (key, default = None): Similar to the get () method. If the dictionary does not contain a key, the value is assigned by dict [key] = default.

Update (dict2): Add the dictionary dict2 key-value pairs to the current dictionary.

Values (): Returns a list containing all values in the dictionary.

 

The following is a simulationUser LogonThe data system is used as an example to describe how to use the dictionary.

 

#!/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:', name else: print 'login failure' def showmenu(): prompt = """ (R)eister (L)ogin (Q)uit Enter choice: """ done = False while not done: chosen = False while not chosen: try: choice = raw_input(prompt).strip()[0].lower() except (EOFError, KeyboardInterrupt): 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__': showmenu()

 

The third row of the script initializes an empty db dictionary, and the second row uses has_key () to determine whether the newly registered username (Dictionary key) exists, the second line uses square brackets [] to add a password to a user name (that is, to add a value to a key), and the second line uses get () obtain the password corresponding to the user name (that is, the value corresponding to the dictionary key ). The strip () of the row 38th is a string processing function, which is used to delete the blank character at the beginning and end of the string.



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.