CS61A Day2 dictionary
dict 字典
dict是python内置的一种和list tuple相区别的数据结构, 即c\c++的map,通过键-值(key-value)存储, 通过hash查找来访问. 比如
>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95
上例中, 'Michael’即是key, 95是它的value.
将元素放入dict可以按照上例在初始时定义,也可以有如下加入元素的方法:
>>> d['Adam'] = 67
>>> d['Adam']
67
由于采用hash散列存放和查找,所以dict在内存存放的顺序和放入dict的顺序没有关系.
因此,dict相较于list会占用更多的内存, 并且key必须是不可变的对象, 如数字, 字符串和元组, 而list就不能作为dict的key.
删除dict的元素时可以有以下方法
del tinydict['Name'] # 删除键是'Name'的条目
tinydict.clear() # 清空字典所有条目, 此时为一空dict
del tinydict # 删除字典
dict 还有一些内置的函数方法,包括items( ), keys( ), values( )等,菜鸟教程有详细的描述
比较dict中value的最大值和最小值
有以下dict,想要求其中value最小的元组
d = {1: 5, 2: 3, 3: 4}
min(d.items(), key= lambda x: x[1])
和其他调用min( )不太一样,这里是从d.items( )中取出第一个元素(即第一个元组)作为x, 进入匿名函数中, 返回其value, 后面相同直到dict最后. 最终min( )中的是[(1, 5), (2, 3), (3, 4)].
下面几行代码就是应用上面的方法来按value升序输出元组:
def dict_to_lst(d):
"""Returns a list containing all the (key, value) pairs in d as two-element
tuples ordered by increasing value.
>>> nums = {1: 5, 2: 3, 3: 4}
>>> dict_to_lst(nums)
[(2, 3), (3, 4), (1, 5)]
>>> words = {'first': 'yes', 'second': 'no', 'third': 'perhaps'}
>>> dict_to_lst(words)
[('second', 'no'), ('third', 'perhaps'), ('first', 'yes')]
"""
result = []
for a in range(len(d)):
pair = min(d.items(), key= lambda x: x[1])
d.pop(pair[0])
result.append(pair)
return result
看完应用再来回顾一下min函数的定义:
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass
可以看到:
- 在参数key为空时, 比较args的内容, 如果args为可迭代的对象如list, tuple, dict, 则会迭代后返回其中最小的元素.
- 在参数key不为空时,对于可迭代的args,先进入迭代,对每次迭代得到的元素放入key参数(是一个fuction)后得到的值进行min操作.
参考资料
- 廖雪峰的python教程dict
https://www.liaoxuefeng.com/wiki/1016959663602400/1017104324028448 - Python学习手册(第四版) p220-236
- 菜鸟教程 dict
https://www.runoob.com/python/python-dictionary.html - python四个带 key 参数的函数(max、min、map、filter)
https://www.cnblogs.com/bigtreei/p/7823205.html
内置函数:min 用法
https://www.cnblogs.com/bigtreei/p/7823266.html - python 使用 max函数求字典的最大值(lambda表达式)
https://blog.csdn.net/sinat_38068807/article/details/86021686
CS61A Day2 dictionary
http://zqizhang.github.io/2022/01/18/CS61A-Day2/