字典(dict)存储的是一组无序列表,存储一系列的键值对数据。

存储方式:

  以Hash表进行存储,典型的以空间换时间的策略。

定义方式:

  空字典:d = {} 或者 d = dict()

  带初始值:d = {‘a’: 1, 'b':  2} 

  取值:通过key值取,d['a']

  修改或新增:通过key值,d['c'] = 3

特性:

  (1)字典为可变类型,其内部元素可动态修改(增删改)

  (2)如果key值重复,后面的数据将覆盖前面的数据。

  (3)Python中所有的类型都能进行字典存储,因为Python中一切皆对象,所有对象都有默认的hash算法和比较算法

  (4)Python 中非基础类型的对象作为key时,将根据对象的地址进行hash和比较运行。

  (5)支持常用内置方法(cmp, len, str)等

常用方法:

  

 

类实例对象作为key值:

 

  实例对象作为key值,是根据对象的地址进行hash计算进行存储的,故每个实例对象都将进行保存。

class Demo(object):

def __init__(self, x):
self.x = x


d = {Demo(1): 1, Demo(2): 2, Demo(1): 3}
for k, v in d.items():
print k.x, v

# ============================
结果:

1 3
2 2
1 1

 重定义Hash算法实现根据对象属性进行存储,需要重构对象的 哈希算法(__hash__)算法和比较算数(__eq__或者__cmp__)

class Demo(object):

def __init__(self, x):
self.x = x

def __hash__(self):
return hash(self.x)

def __eq__(self, other):
return self.x == other.x

# __eq__ 和 __cmp__ 实现一个即可
def __cmp__(self, other):
return 0 if self.x == other.x else 1 if self.x > other.x else -1


d = {Demo(1): 1, Demo(2): 2, Demo(1): 3}
for k, v in d.items():
print k.x, v
# ============================
结果:

  1 3
  2 2

有序字典:

  Python 2.7以上及Python3的collections提供了OrderedDict类,该类可以存储有序字典。

import collections

d = {'2': 2, '1': 1}
print d # {'1': 1, '2': 2}
d = collections.OrderedDict()
d['2'] = 2
d['1'] = 1
for k, v in d.items():
print k, v # 2 2, 1 1
posted on 2020-08-22 19:01  lwp-boy  阅读(158)  评论(0编辑  收藏  举报