Deep understanding of the use of keys in a dictionary in Python

Source: Internet
Author: User
Keys for dictionaries

There is no limit to the values in the dictionary, which can be any Python object, from standard objects to user-defined objects, but the keys in the dictionary are type-restricted.
(1) A key is not allowed to correspond to multiple values
One principle must be clarified: Each key can only correspond to one item. That is, it is not allowed to have multiple values for one key (container objects such as lists, tuples, and other dictionaries are possible). When there is a key conflict (that is, the dictionary key is repeated assignment), take the last (most recent) assignment. Python does not cause an error due to a conflict in the keys in the dictionary, and it does not check for key conflicts because if it does, it checks for each key-value pair assignment, which consumes a certain amount of memory.

  >>> dict1 = {' foo ': 789, ' foo ': ' xyz '}   >>> dict1   {' foo ': ' xyz '}   >>> dict1[' foo '] = 123   >>> Dict1   

(2) The key must be a hash

Most Python objects can be keys, but they must be hash-capable objects. mutable types, such as lists and dictionaries, cannot be keys because they are not hashed.
All immutable types are hashed, so they can all be used as keys to the dictionary. To illustrate: numbers with equal values represent the same key, that is, the hash values for integer number 1 and floating point 1.0 are the same, and they are the same key.
At the same time, there are some mutable objects (rarely) that are hashed, and they can be used as keys to the dictionary, but it is rare. For example, a class that implements the __hash__ () Special method. Because the __hash__ () method returns an integer, it is still using the immutable value (the key that makes the dictionary).
Why does the key have to be hashed? The interpreter calls the hash function to calculate the location where your data is stored, based on the value of the key in the dictionary. If the key is a Mutable object, its value can be changed. If the key changes, the hash function maps to a different address to store the data. If such a situation occurs, the hash function cannot reliably store or fetch the relevant data. The reason to choose a hash key is because its value cannot be changed.
Numbers and strings can be used as a dictionary key, tuples are immutable but may not be immutable, so the use of tuples to make valid keys must be restricted: if the meta
Only immutable parameters such as numbers and strings can be included in a group as valid keys in a dictionary.

Example:
# VI userpw.py

#!/usr/bin/env python

db = {}def NewUser (): prompt= ' please regist your name: ' While true:name = Raw_input (Prompt) if Db.has_key (name)   : prompt = ' name taken,try another: ' Continue else:break pwd = Raw_input (' passswd: ') db[name] = pwd print ' NewUser [%s] has added successfully! '%namedef olduser (): name = Raw_input (' login: ') pwd = Raw_input (' passwd: ') passwd = db.get (name) if passwd = = Pwd:print ' Welcome back ', name else:print ' login incorrect! '  Def showmenu (): prompt = "" "(N) EW user login (E) xisting user Login (Q) uitenter choice:" "While True:try:choice  = Raw_input (Prompt). Strip () [0].lower () print ' \nyou picked: [%s] '% choice if choice not in ' NEQ ': print  ' Invalid option,please try again ' if choice = = ' n ': NewUser () if choice = = ' E ': Olduser () if Choice = = ' Q ': Break except (eoferror,keyboardinterrupt): print ' Invalid option,please try again ' if __name_ _ = = ' __main__ ': ShowMenu ()
  • 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.