A dictionary in Python is a data structure for key-value mapping in Python.Here's how to operate the dictionary,Hope everyone likes it

The keys in the dictionary must meet the following two conditions:

1. Each key can only correspond to one item.That is,Not allowed when one key corresponds to multiple values ​​(except container objects for lists, tuples, and other dictionaries). When a key conflicts (that is, a dictionary key is repeatedly assigned), the last assignment is taken.

>>>myuniversity_dict={"name":"yuanyuan", "age":18, "age":19, "age":20, "schoolname":chengdu, "schoolname":xinxiang}
traceback (most recent call last):
 file "<stdin>", line 1, in<module>
nameerror:name "chengdu" is not defined
>>>myuniversity_dict={"name":"yuanyuan", "age":18, "age":19, "age":20, "schoolname":"chengdu", "schoolname":"xinxiang" }
{"age":20, "name":"yuanyuan", "schoolname":"xinxiang"}

2. The keys must be hashable.Mutable types like lists and dictionaries,Since they are not hashable,So it cannot be used as a dictionary key.

why?-The interpreter calls a hash function,Calculate where your data is stored based on the values ​​of the keys in the dictionary.If the key is a mutable object,You can modify the key itself,Then when the key changes,Hash functions are mapped to different addresses to store data,In this way, it is impossible for the hash function to reliably store or retrieve related data; The reason for choosing hashable keys is that their values ​​cannot be changed.An example of an excerpt from the core python programming (second edition) is as follows:

#!/usr/bin/env python
def newuser ():
  prompt="login desired:"
  while true:
    name=raw_input (prompt)
    if db.has_key (name):
      prompt="name taken, try another \ n"
  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 "welcome back", name
    print "login incorrect"
def showmenu ():
  prompt="" "
(n) ew user login
(e) xisting user login
(q) uit
enter choice:"" "
  while not done:
    while not chosen:
        choice=raw_input (prompt) .strip () [0] .lower ()
      print "\ nyou picked:[%s]"%choice
      if choice not in "neq":
        print "invalid option, try again"
    if choice == "q":done=true
    if choice == "n":newuser ()
    if choice == "e":olduser ()
if __name__ == "__main__":
  showmenu ()

operation result:

[[email protected] src] #python usrpw.py
(n) ew user login
(e) xisting user login
(q) uit
enter choice:n
you picked:[n]
login desired:root
(n) ew user login
(e) xisting user login
(q) uit
enter choice:n
you picked:[n]
login desired:root
name taken, try another
  • Previous Detailed explanation and simple examples of AngularJS ng-change directive
  • Next C # method to clear cookie cache in WebBrowser