python中的字典使用分享

yipeiwu_com6年前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

相关文章

让你Python到很爽的加速递归函数的装饰器

今天我们会讲到一个[装饰器] 注记:链接“装饰器”指Python3教程中的装饰器教程。可以在这里快速了解什么是装饰器。 @functools.lru_cache——进行函数执行结果备忘,...

Python 多个图同时在不同窗口显示的实现方法

Python的matplotlib包可以轻松的将数据可视化,博主最近遇到了一个问题,博主想同时在两个窗口展示两张图,但是代码运行结果总是显示一张图,把当前的图删掉之后才能显示另一张图。网...

python实现局域网内实时通信代码

使用场景,本地服务器一直在运算数据,实时发送这些数据给客户端,本地局域网内其他客户,可以实时连接服务器,获取服务器数据,互不影响。 python2服务端 #-*- coding:ut...

python判断文件是否存在,不存在就创建一个的实例

如下所示: try: f =open("D:/1.txt",'r') f.close() except IOError: f = open("D:/1.txt",'w')...

python打印异常信息的两种实现方式

1. 直接打印错误 try: # your code except KeyboardInterrupt: print("quit") except Excepti...