Python 字典
来源:互联网 发布:matlab矩阵点乘 编辑:程序博客网 时间:2024/05/01 05:21
前言: 话说前几天在segmentfault.com回答了个问题:怎样将包含元组的列表转换为字典?刚好这几天读了几篇关于Python dict的文章(可点击参考文献看),因此写篇小文做个笔记。本文不能算严格意义的原创,也算是翻译+自己的一些理解,因此归为原创,故建议看看参考文献中的原文。
小TIips:学Python的某个库或者函数等最直接的办法我觉得是在Python shell里敲下help(),如本文要讲的help(dict),或者是dir(dict)查看属性和方法,当然还可查文档了。
判断dict是否含有某键key
过时方法:
dct.has_key(key)符合Python方法
key in dct
那判断key不在字典里呢?
not key in dct
上面显然不太符合英文习惯,推荐方法
key not in dct
将元祖列表转换成字典
ls= [ (‘a’, 1), (‘a’, 2), (‘c’, 3), (‘d’, 4), (‘d’, 5), (‘f’, 6)]转换成dt = { 'a': [1, 2], 'c': 3, 'd': [4, 5], 'f': 6}
方法一:dt = {}for (m,n) in ls: dt.setdefault(m,[]).append(n)方法二:from collections import defaultdictdt = defaultdict(list)for (m,n) in ls: dt.append(n)
上面的两种方法更推荐方法二,defaultdict继续与dict,主要功能是提供字典的值为默认值类型,再讲下文献2中用defaultdict生成树的数据结构,如下:
def tree(): return defaultdict(tree)
上面返回一个默认值类型是自身tree的tree数据结构,看看如何使用它:
users = tree()users['harold']['username'] = 'hrldcpr'users['handler']['username'] = 'matthandlersux'
上面产生一个JSON风格的字典树,我们可以打印它:
print(json.dumps(users))结果如下:
{"harold": {"username": "hrldcpr"}, "handler": {"username": "matthandlersux"}}
文中提到不用设置值也可以,如下:
taxonomy = tree()taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Felis']['cat']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Felidae']['Panthera']['lion']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['dog']taxonomy['Animalia']['Chordata']['Mammalia']['Carnivora']['Canidae']['Canis']['coyote']taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['tomato']taxonomy['Plantae']['Solanales']['Solanaceae']['Solanum']['potato']taxonomy['Plantae']['Solanales']['Convolvulaceae']['Ipomoea']['sweet potato']写个函数打印它们:
def dicts(t): return {k: dicts(t[k]) for k in t}
{'Animalia': {'Chordata': {'Mammalia': {'Carnivora': {'Canidae': {'Canis': {'coyote': {}, 'dog': {}}}, 'Felidae': {'Felis': {'cat': {}}, 'Panthera': {'lion': {}}}}}}}, 'Plantae': {'Solanales': {'Convolvulaceae': {'Ipomoea': {'sweet potato': {}}}, 'Solanaceae': {'Solanum': {'potato': {}, 'tomato': {}}}}}}
再说下collections模块下的Counter用法,如其名,统计计数用的,来个例子:
>>> from collections import Counter>>> d = [1, 1, 1, 2, 2, 3, 1, 1]>>> Counter(d)Counter({1: 5, 2: 2, 3: 1})
一个更完整的例子:
>>> counter = Counter()... for _ in range(10):... num = int(raw_input("Enter a number: "))... counter.update([num]) ...... for key, value in counter.iteritems():... print "You have entered {}, {} times!".format(key, value) Enter a number: 1Enter a number: 1Enter a number: 2Enter a number: 3Enter a number: 51Enter a number: 1Enter a number: 1Enter a number: 1Enter a number: 2Enter a number: 3You have entered 1, 5 times!You have entered 2, 2 times!You have entered 3, 2 times!You have entered 51, 1 times!
其实collections模块是相当好用的呀,还有很多有用的东西,下次再介绍下其他的,具体看文献3,就是官方文档内容。
参考文献:
1。http://blog.amir.rachum.com/post/39501813266/python-the-dictionary-playbook
2. https://gist.github.com/2012250
3. http://docs.python.org/3/library/collections.html?highlight=collections#collections
- Python 字典
- python 字典
- Python:字典
- Python 字典
- python字典
- Python 字典
- python 字典
- python 字典
- Python 字典
- Python字典
- python 字典
- python字典
- python 字典
- python 字典
- python--字典
- python 字典
- python字典
- Python---字典
- JVM调优总结(三)--配置示例
- 我在互联网创业失败的启思录(三) –--敢梦想,敢追寻
- 我在互联网创业失败的启思录(四) –--敢梦想,敢追寻
- iOS里的MVC
- 【整理】MySQL引擎
- Python 字典
- expandlistview 展开, group 不可点击
- oracle存储过程使用实例之update的使用
- mysql_connect() 不支持 请检查 PHP 配置的错误
- linux中用到的命令
- 我在互联网创业失败的启思录(五) –--敢梦想,敢追寻
- JVM调优总结(四)--新一代垃圾回收算法G1
- Linux--线程编程
- 最多约数问题答案解析与勘误