字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 (key=>value) 对用冒号(:)分割,每个对之间用逗号 (,) 分割,整个字典包括在花括号 ({}) 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
一个简单的字典实例:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
也可如此创建字典:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
把相应的键放入熟悉的方括弧,如下实例:
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age']; 
以上实例输出结果:
dict['Name']:  Zara
dict['Age']:  7 
如果用字典里没有的键访问数据,会输出错误如下:
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
print "dict['Alice']: ", dict['Alice']; 
以上实例输出结果:
dict['Zara']:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
 
 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
以上实例输出结果:
dict['Age']:  8
dict['School']:  DPS School
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用 del 命令,如下实例:
#coding=utf-8
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典
 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School']; 
但这会引发一个异常,因为用 del 后字典不再存在:
dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable 
注:del() 方法后面也会讨论。
    
字典键的特性
字典值可以没有限制地取任何 Python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
#!/usr/bin/python
 
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
 
print "dict['Name']: ", dict['Name']; 
以上实例输出结果:
dict['Name']:  Manni 
2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
#!/usr/bin/python
 
dict = {['Name']: 'Zara', 'Age': 7};
 
print "dict['Name']: ", dict['Name']; 
以上实例输出结果:
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Zara', 'Age': 7};
TypeError: list objects are unhashable 
Python字典包含了以下内置函数:
| 序号 | 函数及描述 | 
|---|---|
| 1 | cmp(dict1, dict2)
                 比较两个字典元素。  | 
        
| 2 | len(dict)
                 计算字典元素个数,即键的总数。  | 
        
| 3 | str(dict)
                 输出字典可打印的字符串表示。  | 
        
| 4 | type(variable)
                 返回输入的变量类型,如果变量是字典就返回字典类型。  | 
        
Python字典包含了以下内置方法:
| 序号 | 函数及描述 | 
|---|---|
| 1 | radiansdict.clear()
                 删除字典内所有元素  | 
        
| 2 | radiansdict.copy()
                 返回一个字典的浅复制  | 
        
| 3 | radiansdict.fromkeys()
                 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值  | 
        
| 4 | radiansdict.get(key, default=None)
                 返回指定键的值,如果值不在字典中返回 default 值  | 
        
| 5 | radiansdict.has_key(key)
                 如果键在字典 dict 里返回 True,否则返回 False  | 
        
| 6 | radiansdict.items()
                 以列表返回可遍历的(键, 值) 元组数组  | 
        
| 7 | radiansdict.keys()
                 以列表返回一个字典所有的键  | 
        
| 8 | radiansdict.setdefault(key, default=None)
                 和 get() 类似, 但如果键不已经存在于字典中,将会添加键并将值设为 default  | 
        
| 9 | radiansdict.update(dict2)
                 把字典 dict2 的键/值对更新到 dict 里  | 
        
| 10 | radiansdict.values()
                 以列表返回字典中的所有值  | 
        
实例:
使用Python编写字典程序:
    
代码如下:
#coding:utf-8
# 字典创建  while开关 字典添加   字典寻找
dictionary = {}
flag = 'a'
pape = 'a'
off = 'a'
while flag == 'a' or 'c' :
    flag = raw_input("添加或查找单词 ?(a/c)")
    if flag == "a" :                             # 开启
        word = raw_input("输入单词(key):")
        defintion = raw_input("输入定义值(value):")
        dictionary[str(word)] = str(defintion)  # 添加字典
        print "添加成功!"
        pape = raw_input("您是否要查找字典?(a/0)")   #read
        if pape == 'a':
            print dictionary
        else :
            continue
    elif flag == 'c':
        check_word = raw_input("要查找的单词:")  # 检索
        for key in sorted(dictionary.keys()):            # yes
            if str(check_word) == key:
                print "该单词存在! " ,key, dictionary[key]
                break
            else:                                       # no
                off = 'b'
        if off == 'b':
            print "抱歉,该值不存在!"
    else:                               # 停止
        print "error type"
        break
测试结果如下所示:
添加或查找单词 ?(a/c)a
输入单词(key):w3c
输入定义值(value):
添加成功!
您是否要查找字典?(a/0)0
添加或查找单词 ?(a/c)c
要查找的单词:w3c
该单词存在!  w3c 
添加或查找单词 ?(a/c)