Python字典高级使用方法汇总
字典(dictionary)是python中的一种非常灵活和强大的数据结构,可以完成很多操作。本文总结了一些除了基本的初始化、赋值、取值之外的常用的字典使用方法。
字典基础参考:
【1】:http://www.w3cschool.cc/python/python-dictionary.html
【2】:http://www.111cn.net/phper/python/56355.htm
【3】:http://skyfen.iteye.com/blog/567571
【4】:http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html
使用dict创建字典的n种方法
除了我们比较常用的d = {'a':1, 'b':2}
来初始化字典外,还可以使用dict()
来初始化,这种方法更为灵活。以下介绍了用dict来初始化字典的几种方法。
In [2]: dict?
Type: type
String form: <type 'dict'>
Namespace: Python builtin
Docstring:
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
参数赋值
In [6]: d = dict(a=1,b=2)
In [7]: d
Out[7]: {
'a': 1, 'b': 2}
用可迭代对象为参数,且每一个迭代对象为(k, v)
对
In [8]: l1 = ['a', 'b', 'c']
In [9]: l2 = [1, 2, 3]
In [11]: zip(l1,l2)
Out[11]: [('a', 1), ('b', 2), ('c', 3)]
In [12]: d = dict(zip(l1,l2))
In [13]: d
Out[13]: {
'a': 1, 'b': 2, 'c': 3}