字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
一个简单的字典实例:
dic = {'name':'zhang', 'age':'28', 'gender':'Man'}
也可如此创建字典:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
把相应的键放入熟悉的方括弧,如下实例:
#!/usr/bin/python
dict = {'Name': 'Zhang', 'Age': 28, 'From': 'xz'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
以上实例输出结果:
dict['Name']: Zhang
dict['Age']: 28
如果用字典里没有的键访问数据,会输出错误如下:
#!/usr/bin/python
dict = {'Name': 'Zhang', 'Age': 27, 'From': 'xz};
print "dict['Alice']: ", dict['Alice'];
以上实例输出结果:
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
#!/usr/bin/python
dict = {'Name': 'Zhang', 'Age': 27, 'From': 'xz'};
dict['Age'] = 28; # update existing entry
dict['School'] = "xz School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
以上实例输出结果:
dict['Age']: 28
dict['School']: xz School
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zhang', 'Age': 27, 'From': 'xz'};
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
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
#!/usr/bin/python
dict = {'Name': 'Zhang', 'Age': 27, 'Name': 'Minni'};
print "dict['Name']: ", dict['Name'];
以上实例输出结果:
dict['Name']: Minni
2**)键必须不可变**,所以可以用数字,字符串或元组充当,所以用列表就不行,如下实例:
#!/usr/bin/python
dict = {['Name']: 'Zhang', 'Age': 27};
print "dict['Name']: ", dict['Name'];
以上实例输出结果:
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zhang', 'Age': 27};
TypeError: list objects are unhashable
Python字典包含了以下内置函数:
1 cmp(dict1, dict2) 比较两个字典元素。
2 len(dict) 计算字典元素个数,即键的总数。
3 str(dict) 输出字典可打印的字符串表示。
4 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。
Python字典包含了以下内置方法:
1 dict.clear() 删除字典内所有元素
2 dict.copy() 返回一个字典的浅复制
3 dict.fromkeys(seq[, val]) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
4 dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
5 dict.has_key(key) 如果键在字典dict里返回true,否则返回false
6 dict.items() 以列表返回可遍历的(键, 值) 元组数组
7 dict.keys() 以列表返回一个字典所有的键
8 dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 dict.update(dict2) 把字典dict2的键/值对更新到dict里
10 dict.values() 以列表返回字典中的所有值
11 pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem() 随机返回并删除字典中的一对键和值。
在没有认识字典前,我们使用元祖来创建:
In [36]: info = ('name','age')
In [37]: info1 = ('zhang','28')
In [38]: zip(info,info1) //合并收集
Out[38]: [('name', 'zhang'), ('age', '28')]
元祖:
如果后期我需要增加一个新的元素或者修改,但是元祖的元素后期是不可以更改和添加的。
列表:
列表是可以增删改查,但是当我们的元素有很多,取值就很不方便了!
我们可以使用 “字典”: 创建字典:
①: dic1 = {'aa':'asd','123':'111',('a','b'):'hello'} //字典可以为字符串,元祖等,但不能为list,因为list的值是可以变的。
②: dict(x=11,y=12)
Out[79]: {'x': 11, 'y': 12}
//以下两种的值都是样的:
③: dic3.fromkeys('asd',100) //创建一个值为一样的字典数列
Out[74]: {'a': 100, 'd': 100, 's': 100}
④: dic3.fromkeys(range(5),'as')
Out[75]: {0: 'as', 1: 'as', 2: 'as', 3: 'as', 4: 'as'}
In [43]: len(dic1) //查看字典中的元素
Out[43]: 3
In [44]: dic1.
dic1.clear dic1.get dic1.iteritems dic1.keys dic1.setdefault dic1.viewitems
dic1.copy dic1.has_key dic1.iterkeys dic1.pop dic1.update dic1.viewkeys
dic1.fromkeys dic1.items dic1.itervalues dic1.popitem dic1.values dic1.viewvalues
In [44]: dic1.keys() //用列表的形式显示字典中的key
Out[44]: ['aa', ('a', 'b'), '123']
In [45]: dic1.values() //用列表的形式显示字典中的values
Out[45]: ['asd', 'hello', '111']
In [46]: dic1.get('123') //查看key为123的值
Out[46]: '111'
In [47]: dic1 //key的值是唯一的
Out[47]: {'123': '111', 'aa': 'asd', ('a', 'b'): 'hello'}
In [48]: dic1['123'] = 222 //更改key的值
In [49]: dic1
Out[49]: {'123': 222, 'aa': 'asd', ('a', 'b'): 'hello'}
In [51]: dic1[('a','b')] = 'python'
In [52]: dic1
Out[52]: {'123': 222, 'aa': 'asd', ('a', 'b'): 'python'}
In [53]: dic1.get('qwe','324') //假如字典中没有,你可以自己给一个返回值
Out[53]: '324'
In [54]: dic1.items() //返回值为列表模式
Out[54]: [('aa', 'asd'), (('a', 'b'), 'python'), ('123', 222)]
In [55]: dic2 = dic1.copy() //copy一下
In [56]: dic2
Out[56]: {'123': 222, 'aa': 'asd', ('a', 'b'): 'python'}
In [57]: dic2.clear() //清除字典中的元素
In [58]: dic2
Out[58]: {}
In [69]: dic1.pop('aa') //删除aa这个key和value
Out[69]: 'asd'
In [70]: dic1.pop('asas','not exist') //删除一个值并指定一个返回值
Out[70]: 'not exist'
In [71]: dic3 = {'11':'1212','22':'2222'}
In [72]: dic1.update(dic3) //把dic3字典中的值更新到dic1中
In [73]: dic1
Out[73]: {'11': '1212', '123': 222, '22': '2222', ('a', 'b'): 'python'}
使用 for 循环 打印values
In [82]: dic1
Out[82]: {'11': '1212', '123': 222, '22': '2222', ('a', 'b'): 'python'}
In [83]: for k in dic1:
...: print k
...:
11
('a', 'b')
123
22
//打印 keys 和 values
In [84]: for k in dic1:
...: print k, dic1[k]
...:
11 1212
('a', 'b') python
123 222
22 2222
In [86]: for k in dic1:
...: print "%s: %s" % (k, dic1[k])
...:
11: 1212
('a', 'b'): python
123: 222
22: 2222
练习下:
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# @Time : 12/23/2017 2:49 PM
# @Author : Zhdya
# @Email : zhdya@zhdya.cn
# @File : test_1222.py
# @Software: PyCharm
info = {} ## 定义一个空字典
name = raw_input("pls input a name: ")
age = raw_input("pls input your age: ")
gender = raw_input("pls input your gender (M/F): ")
info['name'] = name ##把接收到的值传给info这个字典
info['age'] = age
info['gender'] = gender
for k, v in info.items(): ##for循环打印各个items
print "%s: %s" % (k, v)
输出:
pls input a name: zhang
pls input your age: 22
pls input your gender (M/F): M
gender: M
age: 22
name: zhang
练习题目(2):
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# @Time : 12/23/2017 2:49 PM
# @Author : Zhdya
# @Email : [email protected]
# @File : test_1222.py
# @Software: PyCharm
# info = {} ## 定义一个空字典
# name = raw_input("pls input a name: ")
# age = raw_input("pls input your age: ")
# gender = raw_input("pls input your gender (M/F): ")
#
# info['name'] = name ##把接收到的值传给info这个字典
# info['age'] = age
# info['gender'] = gender
#
# for k, v in info.items():
# print "%s: %s" % (k, v)
#
# 1. 现有一个字典dict1 保存的是小写字母a-z对应的ASCII码
dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
#
# 1) 将该字典按照ASCII码的值排序
print sorted(dict1.iteritems(), key=lambda d:d[1]) ##itemritems是一个迭代函数(用起来比较省内存) 命名一个匿名函数,传入的参数是d 返回值是d[1]的值 1就是values的值,0为key的值。
# 2) 有一个字母的ASCII错了,修改为正确的值,并重新排序
dict1['o'] = 111
dict2 = sorted(dict1.iteritems(), key=lambda d:d[1])
print dict2
# 2. 用最简洁的代码,自己生成一个大写字母 A-Z 及其对应的ASCII码值的字典dict2(使用dict,zip,range方法)
# A~Z:65-90
import string
# ss = string.uppercase #先一步步的找灵感
# rr = range(65,90)
# aa = zip(ss,rr)
# print aa
dict4 = dict(zip(string.uppercase,range(65,91)))
print dict4
# 3. 将dict4与第一题排序后的dict2合并成一个dict5
dict5 = dict(dict2, **dict4) # dict() 函数用于创建一个字典。
print dict5
#
# dict 语法:
# class dict(**kwarg)
# class dict(mapping, **kwarg)
# class dict(iterable, **kwarg)
# 参数说明:
# **kwargs -- 关键字
# mapping -- 元素的容器。
# iterable -- 可迭代对象。
编写字典程序:
1. 用户添加单词和定义
2. 查找这些单词
3.如果查不到,请让用户知道
4. 循环
#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):runoob
输入定义值(value):www.runoob.com
添加成功!
您是否要查找字典?(a/0)0
添加或查找单词 ?(a/c)c
要查找的单词:runoob
该单词存在! runoob www.runoob.com
添加或查找单词 ?(a/c)