A deep understanding of the use of dictionary keys in Python and a deep understanding of the python dictionary

Source: Internet
Author: User

A deep understanding of the use of dictionary keys in Python and a deep understanding of the python dictionary

Dictionary key

The value in the dictionary has no restrictions. It can be any Python object, that is, from a standard object to a user-defined object. However, the keys in the dictionary have type restrictions.
(1) One key cannot correspond to multiple values.
One principle must be clarified: each key can correspond to only one item. That is to say, multiple values corresponding to one click are not allowed (container objects such as lists, tuples, and other dictionaries are acceptable ). When a key conflict occurs (that is, the dictionary key is assigned a value repeatedly), the last (most recent) value is assigned. Python does not generate an error because of a key conflict in the dictionary. It does not check the key conflict because, if so, it checks every key-value pair when assigning values, this will occupy a certain amount of memory.

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

(2) The key must be Hash-able.

Most Python objects can be used as keys, but they must be Hash objects. Variable types such as lists and dictionaries cannot be used as keys because they are not hash-able.
All unchangeable types can be hashed, so they can be used as Dictionary keys. It should be noted that numbers with equal values represent the same keys, that is, the hash values of integer 1 and floating point 1.0 are the same, and they are the same keys.
At the same time, some variable objects (rarely) can be hashed, which can be used as Dictionary keys, but are rare. For example, a class that implements special _ hash _ () methods. Because the _ hash _ () method returns an integer, it still uses an unchangeable value (as a dictionary key ).
Why must keys be hashable? The interpreter calls the hash function to calculate the location of your data based on the value in the dictionary. If the key is a mutable object, its value can be changed. If the key changes, the hash function maps to different addresses to store data. If this happens, the hash function cannot store or obtain relevant data reliably. The reason for selecting hash keys is that their values cannot be changed.
Numbers and strings can be used as Dictionary keys. tuples are unchangeable but may not remain unchanged. Therefore, when using tuples for valid keys, you must add restrictions:
Only unchangeable parameters such as numbers and strings can be included in the group as valid keys in the 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.