一入python深似海--dict(字典)的一种实现

下面是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(字典)的一种实现

时间: 2024-10-18 13:50:46

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

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

Python中一切皆是对象,每个对象都可以有多个属性.Python是如何管理这些属性呢?我们来探讨一下. 属性的__dict__系统 对象的属性包含两部分:类属性和对象属性.对象的属性可能来自于其类的定义,叫做类属性.类属性可能来自于类的定义自身,也可能来自父类.一个对象的属性还可能是该对象实例定义的,叫做对象属性. 对象的属性存储在对象的__dict__属性中.__dict__为一个字典,键为属性名,对应的值为属性本身.下面是一个例子. class bird(object): feather

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

python中有一个模块copy,deepcopy函数用于深拷贝,copy函数用于浅拷贝.要理解浅拷贝,必须先弄清楚python中的引用. 引用 Python中一切都是对象,变量中存放的是对象的引用.这是一个普遍的法则.可以说 Python 没有赋值,只有引用.如,a=1,变量a只是整数对象1的引用. 可变对象与不可变对象及其引用 一.不可变对象 不可变对象包括:数字,字符串,元组. 由于Python中的变量存放的是对象引用,所以对于不可变对象而言,尽管对象本身不可变,但变量的对象引用是可变的.

一入python深似海--Dictionaries

定义及应用 定义 <span style="font-size:18px;">stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}#key:value pairs</span> 实例 # create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New Yo

一入python深似海--tuple和set

tuple(元组) 另一种有序列表叫元组:tuple.tuple和list非常类似,但是tuple一旦初始化就不能修改,tuple属于不可变对象.比如同样是列出同学的名字: >>> classmates = ('Michael', 'Bob', 'Tracy') 现在,classmates这个tuple不能变了,它也没有append(),insert()这样的方法.其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成

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

一.基本原理 Python中一切都是对象,变量是对象的引用.这是一个普遍的法则.我们举个例子来说,Python是如何来处理的. x = 'blue' y = 'green' z = x 当python执行上面第一句的时候,会在heap中首先创建一个str对象,其文本内容为blue,同时还创建一个名为x的对象引用,x引用的就是这个str对象.第二句也是类似:第三条创建了一个名为z的新对象引用,并将其设置为对象引用x所指向的相同对象.如下图的变化. 所以看出在Python中赋值操作符号"="

一入python深似海--while-loop与for-loop

while loops 定义与实例 i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbe

一入python深似海--list

几个实例展示python中数据结构list的魅力! list变量申明 the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 访问list元素 array= [1,2,5,3,6,8,4] #其实这里的顺序标识是 (0,1,2,3,4,5,6) (-7,-6,-5,-4,-3,-2,-1)#有

一入python深似海--函数与文件

先上写干货,几个开源网站: github.com launchpad.net gitorious.org sourceforge.net freecode.com 今天介绍一下python函数和文件读写的知识. 函数 def print_two(*args):#That tells Python to take all the arguments to the function and then put them in args as a list arg1,arg2=args print "a

一入python深似海--split

mnesia在频繁操作数据的过程可能会报错:** WARNING ** Mnesia is overloaded: {dump_log, write_threshold},可以看出,mnesia应该是过载了.这个警告在mnesia dump操作会发生这个问题,表类型为disc_only_copies .disc_copies都可能会发生. 如何重现这个问题,例子的场景是多个进程同时在不断地mnesia:dirty_write/2 mnesia过载分析 1.抛出警告是在mnesia 增加dump