当前位置:编程学习 > python >>

Python 语法之字典

 
*特点:无序,是唯一内置的映射类型。多用于实现哈希表或者关联数组。
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
{&#
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,