python中的字典使用分享

字典中的键使用时必须满足一下两个条件:

1、每个键只能对应一个项,也就是说,一键对应多个值时不允许的(列表、元组和其他字典的容器对象除外)。当有键发生冲突时(即字典键重复赋值),取最后的赋值。

>>> 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','schoolname':'Chengdu','schoolname':'Xinxiang'}
>>> myuniversity_dict
{'age': 20,'name': 'yuanyuan','schoolname': 'Xinxiang'}
>>>

2、键必须是可哈希的,像列表和字典这样的可变类型,由于他们是不可哈希的,所以不能作为字典的键。

为什么呢?―― 解释器调用哈希函数,根据字典中键的值来计算存储你的数据的位置。如果键是可变对象,可以对键本身进行修改,那么当键发生变化时,哈希函数会映射到不同的地址来存储数据,这样哈希函数就不可能可靠地存储或获取相关的数据; 选择可哈希键的原因就是他们的值不能被改变。摘抄python 核心编程(第二版)的一个实例如下:

#!/usr/bin/env python

db = {}

def newuser():
  prompt = 'login desired: '
  while True:
    name = raw_input(prompt)
    if db.has_key(name):
      prompt = 'name taken,try another\n'
      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 'welcome back',name
  else:
    print 'login incorrect'

def showmenu():
  prompt = """

(N)ew User Login
(E)xisting User Login
(Q)uit

Enter choice:"""
  done = False
  while not done:

    chosen = False
    while not chosen:
      try:
        choice = raw_input(prompt).strip()[0].lower()
      except:
        choice = 'q'
      print '\nYou picked: [%s]' % choice
      if choice not in 'neq':
        print 'invalid option,try again'
      else:
        chosen = True

    if choice == 'q':done = True
    if choice == 'n':newuser()
    if choice == 'e':olduser()

if __name__ == '__main__':
  showmenu()

运行结果:

[root@localhost src]# python usrpw.py 


(N)ew User Login
(E)xisting User Login
(Q)uit

Enter choice:n

You picked: [n]
login desired: root
passwd: 1


(N)ew User Login
(E)xisting User Login
(Q)uit

Enter choice:n

You picked: [n]
login desired: root
name taken,try another

相关文章

方案一 代码 在Python中,可以使用wave模块来读取双通道(立...
简介 一个用python实现的科学计算,包括: 1、一个强大的N维...
使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登...
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登...
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接...
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密...