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', 'age':18, 'age':19, 'age':20, '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

OpenCV官方教程中文版(For Python) PDF 

Ubuntu Linux下安装OpenCV2.4.1所需包

Ubuntu 12.04 安装 OpenCV2.4.2

CentOS下OpenCV无法读取视频文件

Ubuntu 12.04下安装OpenCV 2.4.5总结

Ubuntu 10.04中安装OpenCv2.1九步曲

基于QT和OpenCV的人脸识别系统

[翻译]Ubuntu 14.04, 13.10 下安装 OpenCV 2.4.9 

OpenCV的详细介绍:请点这里
OpenCV的下载地址:请点这里

本文永久更新链接地址

相关内容