首页 > 程序开发 > Web开发 > Python >

Python 语法之字典

2013-03-21

*特点:无序,是唯一内置的映射类型。多用于实现哈希表或者关联数组。key具有唯一性,可以使用固定长度的对象,不能使用列表、字典和包含可变长度类型的元组。访问形式:m[k],k是key。如果找不到,报错:KeyEr...

*特点:无序,是唯一内置的映射类型。多用于实现哈希表或者关联数组。
key具有唯一性,可以使用固定长度的对象,不能使用列表、字典和包含可变长度类型的元组。访问形式:m[k],k是key。如果找不到,报错:KeyError。
定义:
dict(one=1, two=2) 注意这里的字符串one和two没有引号。
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])
方法和操作如下:
项目
功能
len(m)
Return the number of items in the dictionary d.
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map. dict的子类可以定义 __missing__()改变这点。应用:collections.defaultdict.
d[key] = value
Set d[key] to value.
del d[key]
Remove d[key] from d. Raises a KeyError if key is not in the map.
key in d
Return True if d has a key key, else False.
key not in d
Equivalent to not key in d.
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys()
d.clear()
 Remove all items from the dictionary.
d.copy()
 Return a shallow copy of the dictionary
d.fromkeys(seq[, value])
 创建并返回一个新字典,以seq 中的元素做该字典的键,val 做该字典中所有键对应的初始值(如果不提供此值,则默认为None).类方法。
d. get(key[, default])
 Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
d. has_key(key)
不建议使用
d.items()
Return a copy of the dictionary’s list of (key, value) pairs.
d.iteritems()
Return an iterator over the dictionary’s (key, value) pairs. See the note for dict.items().
d.iterkeys()
Return an iterator over the dictionary’s keys.
d. itervalues()
 Return an iterator over the dictionary’s values.
d.keys()
Return a copy of the dictionary’s list of keys.
d.pop (key[, default])
 If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
d.popitem()
 Remove and return an arbitrary (key, value) pair from the dictionary.
d.setdefault (key[, default])
 If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
d.update(b)
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
d.values()
 Return a copy of the dictionary’s list of values.
d. viewitems()
 Return a new view of the dictionary’s items ((key, value) pairs).
d. viewkeys()
Return a new view of the dictionary’s keys 
d. viewkeys()
 Return a new view of the dictionary’s values. See
其中fromkeys()是类方法。items(),keys(),values()返回的是列表(Python2),Python 3返回的是迭代器,需要这样转换结果:items=list(m.items().
View对象返回的是字典的动态视图。它支持长度,迭代,属于关系等:
len(dictview)Return the number of entries in the dictionary.
iter(dictview)Return an iterator over the keys, values or items (represented as tuples of (key,value)) in thedictionary.
xin dictview Return Trueif x is in the underlying dictionary’s keys, values or items (in thelatter case, x should be a (key, value) tuple).
还支持集合运算:
dictview & other
dictview | other
dictview - other
dictview ^ other 两边不相同的元素。
# python
Python2.7.3 (default, Jan 5 2013, 11:24:11)
[GCC 4.4.620120305 (Red Hat 4.4.6-4)] on linux2
Type"help", "copyright", "credits" or"license" for more information.
>>>dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>>keys = dishes.viewkeys()
>>>keys
dict_keys(['eggs','bacon', 'sausage', 'spam'])
>>>values = dishes.viewvalues()
>>>values
dict_values([2,1, 1, 500])
>>>n = 0
>>>for val in values:
... n += val
...
>>>print(n)
504
>>>list(keys)
['eggs','bacon', 'sausage', 'spam']
>>>list(values)
[2, 1, 1,500]
>>>del dishes['eggs']
>>>del dishes['sausage']
>>>list(keys)
['bacon','spam']
>>>keys & {'eggs', 'bacon', 'salad'}
set(['bacon'])
*构建字典
字典举例:
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil':'3258'}
stock = {
"name" :"GOOG",
"shares": 100,
"price" :490.10
}
name =stock["name"]
value =stock["shares"] * shares["price"]
要特别注意字符串类型时中括号里面的引号。
prices = {} # Anempty dict
prices = dict() #An empty dict
d = { }
d[1,2,3] ="foo" d[(1,2,3)] ="foo"
d[1,0,3] ="bar" d[(1,0,3)] = "bar"
成员关系用in判断:
if "SCOX"in prices:
p = prices["SCOX"]
else:
p = 0.0
更简便的方法:p =prices.get("SCOX",0.0)
获取key为列表:
syms = list(prices)
>>> syms
['GOOG', 'AAPL','IBM', 'MSFT']
删除元素:del prices["MSFT"]
函数Dict可以从其他映射或者序列构建字典
>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
也可以使用参数的方法:
>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
初始化空字典:
>>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}
*格式化输出:
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone numberis %(Cecil)s." % phonebook
"Cecil's phone number is 3258."
>>>template = &#39;&#39;&#39;<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body>&#39;&#39;&#39;
>>> data ={&#39;title&#39;: &#39;My Home Page&#39;, &#39;text&#39;: &#39;Welcome to my home page!&#39;}
>>> printtemplate % data
<html>
<head><title>MyHome Page</title></head>
<body>
<h1>My HomePage</h1>
<p>Welcome tomy home page!</p>
</body>
另外string.Template 类也很适合这种应用。
*字典方法:
-*清除:clear
下面例子展示clear和把字典置空字典的区别:
>>> x = {}
>>> y = x
>>> x[&#39;key&#39;] = &#39;value&#39;
>>> y
{&#39;key&#39;: &#39;value&#39;}
>>> x = {}
>>> y
{&#39;key&#39;: &#39;value&#39;}
>>> x = {}
>>> y = x
>>> x[&#39;key&#39;] = &#39;value&#39;
>>> y
{&#39;key&#39;: &#39;value&#39;}
>>> x.clear()
>>> y
{}
-*复制:copy
>>> x = {&#39;username&#39;: &#39;admin&#39;, &#39;machines&#39;: [&#39;foo&#39;,&#39;bar&#39;, &#39;baz&#39;]}
>>> y = x.copy()
>>> y[&#39;username&#39;] = &#39;mlh&#39;
>>> y[&#39;machines&#39;].remove(&#39;bar&#39;)
>>> y
{&#39;username&#39;: &#39;mlh&#39;, &#39;machines&#39;: [&#39;foo&#39;, &#39;baz&#39;]}
>>> x
{&#39;username&#39;: &#39;admin&#39;, &#39;machines&#39;: [&#39;foo&#39;, &#39;baz&#39;]}
浅拷贝的元素指向原有元素,所以改变原有的可变元素,新的也会受影响,反之亦然。换种说法,对元素进行替换,不会对新老都产生影响,但是修改则会有影响。
>>> from copy import deepcopy
>>> d = {}
>>> d[&#39;names&#39;] = [&#39;Alfred&#39;, &#39;Bertrand&#39;]
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d[&#39;names&#39;].append(&#39;Clive&#39;)
>>> c
{&#39;names&#39;: [&#39;Alfred&#39;, &#39;Bertrand&#39;, &#39;Clive&#39;]}
>>> dc
{&#39;names&#39;: [&#39;Alfred&#39;, &#39;Bertrand&#39;]}
-*复制key:fromkeys
>>> {}.fromkeys([&#39;name&#39;, &#39;age&#39;])
{&#39;age&#39;: None, &#39;name&#39;: None}
也可以用dict代替{}
>>> dict.fromkeys([&#39;name&#39;, &#39;age&#39;])
{&#39;age&#39;: None, &#39;name&#39;: None}
设置其他默认值:
>>> dict.fromkeys([&#39;name&#39;, &#39;age&#39;], &#39;(unknown)&#39;)
{&#39;age&#39;: &#39;(unknown)&#39;, &#39;name&#39;: &#39;(unknown)&#39;}
-*获取:get
>>> d = {}
>>> print d[&#39;name&#39;]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: &#39;name&#39;
>>> print d.get(&#39;name&#39;)
None
也可以用其他字符替代None
>>> d.get(&#39;name&#39;, &#39;N/A&#39;)
&#39;N/A&#39;
-*列出值:items and iteritems
>>> d = {&#39;title&#39;: &#39;Python Web Site&#39;, &#39;url&#39;:&#39;http://www.python.org&#39;, &#39;spam&#39;: 0}
>>> d.items()
[(&#39;url&#39;, &#39;http://www.python.org&#39;), (&#39;spam&#39;, 0), (&#39;title&#39;,&#39;Python Web Site&#39;)]
>>> it = d.iteritems()
>>> it
<dictionary-iterator object at 169050>
>>> list(it) # Convert the iterator to a list
[(&#39;url&#39;, &#39;http://www.python.org&#39;), (&#39;spam&#39;, 0), (&#39;title&#39;,&#39;Python Web Site&#39;)]
Iteritems生成迭代器,一般的情况下使用iteritems比iteritem更有效,尤其是循环的时候。
注:Python 3 items 返回的是迭代器
-*列出关键字:keys and iterkeys
后者是迭代器
根据key出栈:pop
>>> d = {&#39;x&#39;: 1, &#39;y&#39;: 2}
>>> d.pop(&#39;x&#39;)
1
>>> d
{&#39;y&#39;: 2}
-*出栈:popitem
>>> d
{&#39;url&#39;:&#39;http://www.python.org&#39;, &#39;spam&#39;: 0, &#39;title&#39;: &#39;Python Web Site&#39;}
>>>d.popitem()
(&#39;url&#39;,&#39;http://www.python.org&#39;)
>>> d
{&#39;spam&#39;: 0,&#39;title&#39;: &#39;Python Web Site&#39;}
出栈和列表和类似,但是没有append。
-*setdefault:设置默认值。
>>> d = {}
>>>d.setdefault(&#39;name&#39;, &#39;N/A&#39;)
&#39;N/A&#39;
>>> d
{&#39;name&#39;: &#39;N/A&#39;}
>>>d[&#39;name&#39;] = &#39;Gumby&#39;
>>>d.setdefault(&#39;name&#39;, &#39;N/A&#39;)
&#39;Gumby&#39;
>>> d
{&#39;name&#39;: &#39;Gumby&#39;}
默认值的默认值为None。注意是有值才进行覆盖。
>>> d = {}
>>> printd.setdefault(&#39;name&#39;)
None
>>> d
{&#39;name&#39;: None}
-*更新:update
>>> d = {
&#39;title&#39;: &#39;Python Web Site&#39;,
&#39;url&#39;: &#39;http://www.python.org&#39;,
&#39;changed&#39;: &#39;Mar 14 22:09:15 MET 2008&#39;
}
>>> x = {&#39;title&#39;: &#39;Python Language Website&#39;}
>>> d.update(x)
>>> d
{&#39;url&#39;: &#39;http://www.python.org&#39;, &#39;changed&#39;:
&#39;Mar 14 22:09:15 MET 2008&#39;, &#39;title&#39;: &#39;Python LanguageWebsite&#39;}
-*取值:values and itervalues
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
[1, 2, 3, 1]
相关文章
最新文章
热点推荐