以下是python中字典的一种实现。用list数据结构实现字典。详细是这种:[[(key1,value1),(key2,value2),...],[],[],...]

内部每个hash地址是一个list,存放hash地址同样的(key,value)对。

dict代码

def Map(num_buckets=256):
"""Initializes a Map with the given number of buckets."""
aMap = []
for i in range(0, num_buckets):
aMap.append([])
return aMap def Map_hash(aMap, key):
"""Given a key this will create a number and then convert it to
and index for the aMap's buckets."""
return hash(key) % len(aMap) def Map_get_bucket(aMap, key):
"""Given a key, find the bucket where it would go."""
bucket_id = Map_hash(aMap, key)
return aMap[bucket_id] def Map_get_slot(aMap, key, default=None):
"""Returns the index, key, and value of a slot found in a bucket."""
bucket = Map_get_bucket(aMap, key) for i, kv in enumerate(bucket):#bucket=[[k1,v1],[k2,v2],...]
k, v = kv
if key == k:
return i, k, v#ex1:i=0,k=k1,v=v1 return -1, key, default def Map_get(aMap, key, default=None):
"""Gets the value in a bucket for the given key, or the default."""
i, k, v = Map_get_slot(aMap, key, default=default)
return v def Map_set(aMap, key, value):
"""Sets the key to the value, replacing any existing value."""
bucket = Map_get_bucket(aMap, key)
i, k, v = Map_get_slot(aMap, key) if v:
bucket[i] = (key, value)#key/value pair
else:
bucket.append((key, value)) def Map_delete(aMap, key):
"""Deletes the given key from the Map."""
bucket = Map_get_bucket(aMap, key) for i in xrange(len(bucket)):
k, v = bucket[i]
if key == k:
del bucket[i]
break def Map_list(aMap):
"""Prints out what's in the Map."""
for bucket in aMap:
if bucket:
for k, v in bucket:
print k, v # The tests that it will work. jazz = Map()
Map_set(jazz, 'Miles Davis', 'Flamenco Sketches')
# confirms set will replace previous one
Map_set(jazz, 'Miles Davis', 'Kind Of Blue')
Map_set(jazz, 'Duke Ellington', 'Beginning To See The Light')
Map_set(jazz, 'Billy Strayhorn', 'Lush Life') print "---- List Test ----"
Map_list(jazz) print "---- Get Test ----"
print Map_get(jazz, 'Miles Davis')
print Map_get(jazz, 'Duke Ellington')
print Map_get(jazz, 'Billy Strayhorn') print "---- Delete Test ----"
print "** Goodbye Miles"
Map_delete(jazz, "Miles Davis")
Map_list(jazz) print "** Goodby Duke"
Map_delete(jazz, "Duke Ellington")
Map_list(jazz) print "** Goodbye Billy"
Map_delete(jazz, "Billy Strayhorn")
Map_list(jazz) print "** Goodbye Pork Pie Hat"
Map_delete(jazz, "Charles Mingus")

Map_hash()函数的解释例如以下:


This deceptively simple function is the core of how a dict (Map) works. What it does is uses the built-in Python hash function to convert a string to
a number. Python uses this function for its own dict data structure, and I'm just reusing it. You should fire up a Python console to see how it works. Once I have a number for the key, I then use the % (modulus)
operator and thelen(aMap) to get a bucket where this key can go. As you should know, the % (modulus)
operator will divide any number and give me the remainder. I can also use this as a way of limiting giant numbers to a fixed smaller set of other numbers. If you don't get this then use Python to explore it.

一入python深似海--dict(字典)的一种实现的更多相关文章

  1. 一入python深似海--浅拷贝与深拷贝

    python中有一个模块copy,deepcopy函数用于深拷贝,copy函数用于浅拷贝. 要理解浅拷贝,必须先弄清楚python中的引用. 引用 Python中一切都是对象,变量中存放的是对象的引用 ...

  2. 一入python深似海--对象的属性

    Python中一切皆是对象,每一个对象都能够有多个属性.Python是怎样管理这些属性呢?我们来探讨一下. 属性的__dict__系统 对象的属性包括两部分:类属性和对象属性.对象的属性可能来自于其类 ...

  3. 一入python深似海--class

    python class 分为三个部分:class and object(类与对象),inheritance(继承),overload(重载)and override(覆写). class and o ...

  4. 一入python深似海--变量和对象

    一.基本原理 Python中一切都是对象,变量是对象的引用. 这是一个普遍的法则.我们举个样例来说.Python是怎样来处理的. x = 'blue' y = 'green' z = x 当pytho ...

  5. 一入python深似海--range()、list与for

    range使用方法 使用python的人都知道range()函数非常方便,今天再用到他的时候发现了非常多曾经看到过可是忘记的细节. 这里记录一下: range(1,5)#代表从1到5(不包括5) [1 ...

  6. 一入python深似海--python之道

    python社区不乏幽默.先来看"python之道"这首诗. 导入this包: import this 输出是一首诗,这首诗总结了Python的风格,能够指导Python程序猿的编 ...

  7. 一入Python深似海--print

    先给大家来个干货^~^,学习Python的一个好站点,http://learnpythonthehardway.org/book/ 经典样例 以下是几个老经典的样例喽,刚接触Python的能够敲一敲, ...

  8. 「一入 Java 深似海 」系列课程

    第一期 「一入 Java 深似海 」系列课程 - 第一期 第一节:Java 语言基础

  9. 一入爬虫深似海,从此游戏是路人!总结我的python爬虫学习笔记!

    前言 还记得是大学2年级的时候,偶然之间看到了学长在学习python:我就坐在旁边看他敲着代码,感觉很好奇.感觉很酷,从那之后,我就想和学长一样的厉害,就想让学长教我,请他吃了一周的饭,他答应了.从此 ...

随机推荐

  1. Jedis的Sharded源代码分析

    概述 Jedis是Redis官方推荐的Java客户端,更多Redis的客户端可以参考Redis官网客户端列表.当业务的数据量非常庞大时,需要考虑将数据存储到多个缓存节点上,如何定位数据应该存储的节点, ...

  2. HDU 5765 Bonds 巧妙状压暴力

    题意:给一个20个点无向连通图,求每条边被多少个极小割集包括 分析:极小割集是边的集合,很显然可以知道,极小割集恰好吧原图分成两部分(这个如果不明白可以用反证法) 然后就是奉上官方题解:http:// ...

  3. POJ 3621 Sightseeing Cows 01分数规划,最优比例环的问题

    http://www.cnblogs.com/wally/p/3228171.html 题解请戳上面 然后对于01规划的总结 1:对于一个表,求最优比例 这种就是每个点位有benefit和cost,这 ...

  4. IOS 时间 日历 处理集合

    1.获得当前时间 从1970开始的秒数 NSTimeInterval time = [[NSDate date[ timeIntervalSince1970]]; NSString * str = [ ...

  5. ASP.NET常用技巧方法代码断

    1. 打开新的窗口并传送参数:传送参数:response.write("<script>window.open('*.aspx?id="+this.DropDownLi ...

  6. 机器学习真的可以起作用吗?(2)(以二维PLA算法为例)

    一个问题:大多数情况下,M(hypothesis set的大小)是无穷大的,例如PLA算法.那么是不是我们的原则1就不能使用了? 我们试着做一些努力: Step1:寻找hypothesis set的e ...

  7. 我需要在电脑上安装C编译器

    这本书中我们使用了gcc(GNU编译器套装),它不但功能十分强大,而且还是免费的.你需要确保你的电脑上已经安装了gcc.如果你的操作系统是Linux,恭喜你,你已经拥有了gcc.

  8. Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing

    Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing   ...

  9. 【Hadoop代码笔记】Hadoop作业提交之TaskTracker 启动task

    一.概要描述 在上篇博文描述了TaskTracker从Jobtracker如何从JobTracker获取到要执行的Task.在从JobTracker获取到LaunchTaskAction后,执行add ...

  10. Deep Learning Practice【开篇】

    Chapter 0 初入深度学习实战 最近一直在学习深度学习相关的知识,看文献,看博客,看书,与别人讨论,等等,但是总觉得这样的学习只是停留在表面,无法去深入的学习到深度学习的内幕.于是,决定开始深度 ...