字典

字典类似于列表,但更加通用

键值对 ,字典是 键与值之间的映射,每个键都映射到一个值上

dict可以创建一个不包含任何项的字典

eng2sp = dict()
print eng2sp

还可以给字典添加新项

eng2sp['one']='SS'
print eng2sp

或者直接赋值

eng2sp = {
'one':'1',
'two':"2",
'three':"3"
}
print eng2sp
print eng2sp['one']

len可以用在字典上

print len(eng2sp)

如果一个键不在字典里面,输出就会报错,可以用in判断

print 'one' in eng2sp

使用字典作为计数器

比如计算每个字幕出现次数

def histogram(s):
d = dict()
for i in s:
if i in d:
d[i] +=1
else:
d[i] = 1
return d
w = histogram("brontosaurus")

循环和字典

如果在for循环中使用字典,会遍历字典的键

def print_hist(h):
for c in h:
print c,h[c]
print_hist(w2)

反向查找

给定一个字典d和键k,找到v是很容易的。 但是给定值v 通过v来查找k 就没那么简单了,因为很可能多个k的值是同一个。

初级版本:

def reverse_lookup(d,v):
for k in d:
if d[k]==v:
return k
raise ValueError

字典和列表

列表可以在字典中以值得形式出现

例如

def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse ```
利用字典来实现缓存
我们之前的`fibonacci`函数 会重复计算一些已经计算过的值,那么我们建一个 字典 缓存起来,如果计算过 就返回这个值。

known = {0:0,1:1}

def fibonacci(n):

if n in known:

return known[n]

res = fibonacci(n-1)+fibonacci(n-2)

known[n]=res

return res

ackermann 也可以简历一个缓存

cache = {}

def ackermann(m, n):

if m == 0:

return n+1

if n == 0:

return ackermann(m-1, 1)

try:

return cache[m, n]

except KeyError:

cache[m, n] = ackermann(m-1, ackermann(m, n-1))

return cache[m, n]

练习
1. 读入'words.txt'并将单词以字典的形式存储
    def get_words():
r = []
lin = open('words.txt')
for line in lin:
word = line.strip()
r.append(word)
return r
words = get_words() def word2dict(w):
word = dict()
for i in range(len(w)-1):
word[w[i]]=True
return word dict_word=word2dict(words)
2. 利用字典`get`方法,将`histogram`写得更紧凑
def histogram_get(s):
d = dict()
for i in s:
t = d.get(i,0)
d[i] = t+1
return d w2 = histogram_get("brontosaurus")
3. 字典方法有一个keys,以列表的方式返回字典所有的键,修改`print_hist`按照字典顺序打印字典的键和他们的值
def print_keys(h):
r = h.keys()
for i in r:
print i,h[i] print_keys(w2)
4. 修改`reverse_lookup`使它建立一个包含所有映射到v键的列表
def reverse_lookup2(d,v):
r = []
for k in d:
if d[k]==v:
r.append(k) return r
5. 利用`setdefault`来写个更简洁的`invert_dict`
def invert_dict2(d):
inverse = dict()
for key in d:
inverse.setdefault(d[key],[]).append(key)
return inverse

术语表
- 字典(dictionary):从键的集合到对应的值的集合的映射
- 键值对(key-value pair):键到值得映射的战士
- 项(item):键值对的另一个名称
- 键(key):字典中出现在键值对的前一部分的对象
- 值(value):字典中出现在键值对后一部分的对象
- 实现(implementation):进行计算的一个具体方式
- 散列表(hashtable):python字典的是先用的算法
- 散列函数(hash function):散列表中用来计算一个键的位置的函数
- 可散列(hashable):拥有散列函数的类型
- 查找(lookup):字典的一个操作,接受一个键,并找到它对应的值。
- 反向查找(reverse lookup):字典的一个操作,通过一个值来找到它对应的一个或多个键
- 单件(singleton):只包含一个元素的列表
- 直方图(histogram):一个计数器的集合
- 备忘(memo):将计算结果存储起来,以避免将来进行不必要的计算
- 标志(flag):用于标记一个条件是否为真的布尔变量

think in python 11 字典的更多相关文章

  1. Python的字典

    1.  Python的字典 1.1.  字典的定义 在Python中,字典是一种key-value的数据类型,也是唯一的映射类型:字典还是另一种可变容器类型,且可存储任意类型对象,其中也可包括其他容器 ...

  2. python基础--字典

    Python基础--字典 字典的常用函数: dict.clear( )--->无任何返回值 说明: 清除字典内的所有的元素 语法: In [5]: dict.clear? Type: metho ...

  3. python入门-字典

    1 python是使用{}来表示字典 字典是一系列的键值对 alien_0={} 2 访问字典中的值 new_point = alien_0['point'] print("you just ...

  4. 深入Python(1): 字典排序 关于sort()、reversed()、sorted()

    http://www.cnblogs.com/BeginMan/p/3193081.html 一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠 ...

  5. python中字典排序

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  6. Python中字典和集合

    Python中字典和集合 映射类型: 表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引 与序列不同,映射是无序的,通过键进行索引 任何不可变对象都可用作字典的键,如字符串.数字.元 ...

  7. Python的字典和JSON

    Python的字典和JSON在表现形式上非常相似 #这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'] ...

  8. Python dictionary 字典 常用法

    Python dictionary 字典 常用法 d = {} d.has_key(key_in)       # if has the key of key_in d.keys()          ...

  9. python有序字典OrderedDict()

    转python创建有序字典OrderedDict # -*- coding:utf-8 -*- """ python有序字典 需导入模块collections " ...

随机推荐

  1. POJ 1987 Distance Statistics(树的点分治)

      转载请注明出处,谢谢http://blog.csdn.net/ACM_cxlove?viewmode=contents    by---cxlove 上场CF的C题是一个树的分治... 今天刚好又 ...

  2. Eclipse 常用快捷键 (动画讲解)(转载)

    http://www.cnblogs.com/TankXiao/p/4018219.html#fix 很详细呀/

  3. Binary Tree Level Order Traversal,Binary Tree Level Order Traversal II

    Binary Tree Level Order Traversal Total Accepted: 79463 Total Submissions: 259292 Difficulty: Easy G ...

  4. Python中安装numpy,scipy,matplotlib安装方法

    这个吧,说简单也简单,说难吧我捣鼓了两天才弄出来,真是头发都急白了.其实只要一个网址就搞定了,嘿嘿 http://www.lfd.uci.edu 这里面有你需要的任何东西,当你运行python imp ...

  5. encoding(hdoj1020)

    Problem Description Given a string containing only 'A' - 'Z', we could encode it using the following ...

  6. 烧饼(nyoj779)

    描述烧饼有两面,要做好一个兰州烧饼,要两面都弄热.当然,一次只能弄一个的话,效率就太低了.有这么一个大平底锅,一次可以同时放入k个兰州烧饼,一分钟能做好一面.而现在有n个兰州烧饼,至少需要多少分钟才能 ...

  7. 深入理解Autofac生命周期

    为什么Autofac表现的这样? 这里似乎有几个陷阱,虽然这里只有一个------并且这个值得重申: Autofac将会跟踪每一个他所创建的可销毁的组件实例,无论这个实例是怎样被获取的. 当然,最终. ...

  8. 编译安装mysql5.7.9

    第一步:安装一些可能会用到的依赖 yum -y install gcc-c++ ncurses-devel cmake make perl gcc autoconf automake zlib lib ...

  9. android 遇到的细节 FAQ

    1.ListView 设置addHead 在3.0与之前版本若在:setAdapter之后添加,运行报错.4.0以后不报错 2.ListView  Adapter    getView函数忘记返回vi ...

  10. LINUX USB MASS STORAGE DRIVER流程图