Tips.1 遍历获取嵌套字典中的所有值
http://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values
如果已知字典只有1、2层的话,还可以手动写个for循环,但是如果嵌套层数不确定的话,for循环就不靠谱了,需要使用“递归”的思想了。
def myprint(d): for k, v in d.iteritems(): if isinstance(v, dict): myprint(v) else: print "{0} : {1}".format(k, v)
还有就是利用Python的已有module来帮忙了:
import collections def nested_dict_iter(nested): for key, value in nested.iteritems(): if isinstance(value, collections.Mapping): for inner_key, inner_value in nested_dict_iter(value): yield inner_key, inner_value else: yield key, value >>> list(nested_dict_iter({'a':{'b':{'c':1, 'd':2}, 'e':{'f':3, 'g':4}}, 'h':{'i':5, 'j':6}})) [('c', 1), ('d', 2), ('g', 4), ('f', 3), ('i', 5), ('j', 6)]
另:http://stackoverflow.com/questions/14692690/access-python-nested-dictionary-items-via-a-list-of-keys
Tips.2 Python中iteritems()和items()的区别
搜索:http://cn.bing.com/search?q=dict+iteritems+python
- http://stackoverflow.com/questions/13998492/iteritems-in-python
- http://stackoverflow.com/questions/10458437/what-is-the-difference-between-dict-items-and-dict-iteritems
- http://docs.python.org/library/stdtypes.html#dict.items
- http://docs.python.org/library/stdtypes.html#dict.iteritems
总的来说:在Python 2.x中,items()返回的是实实在在的tuple列表,在某些情况下可能会耗费大量内存;但是iteritems()返回的是一个迭代器,在内存消耗上面可能会好点;不过:Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.
而且在Python 3.x中,iteritems()被删除了,统一用改进过的items()处理相关问题。
Tips.3 在Python中创建嵌套字典的最佳方法
conn = {} tup1 = (s_addr, source_port, d_addr, dest_port, acknowledgement) if tup1 in conn: if sequence in conn[tup1]: conn[tup1][sequence].append(data) else: conn[tup1][sequence] = [data] #conn[tup1] = {sequence:[data]} 这个是错误的方法,每次都是重新赋值! else: conn[tup1] = {sequence:[data]}
- https://docs.python.org/2/library/stdtypes.html#dict.setdefault
- http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python
- http://stackoverflow.com/questions/15819428/how-to-initialize-nested-dictionaries-in-python
Tips.4 Python中嵌套字典内容的更新
将value设置成list类型,然后在碰到相同的key时,往list中append即可。
Tips.5 Python中[嵌套]字典的排序
方法就是:
sortedList = sorted(dic.items(), key=lambda d:d[1], reverse=True)
要注意的就是:
sorted()返回的是一个list,而不是dict。
参考链接:
- http://stackoverflow.com/questions/575819/sorting-dictionary-keys-in-python
- http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
- http://ixyzero.com/blog/archives/824.html
在Python中list和dict的遍历稍有不同:
对于list来说,只需要简单的for循环即可;但是对于dict来说,需要指定items()或iteritems()才行,否则和自己预想的不太一样。
在Python中加载大字典的方法:
http://stackoverflow.com/questions/5248958/fastest-way-to-save-and-load-a-large-dictionary-in-python