字典是python中惟一内建的map类型python
key能够为任何不可改变的类型,包括内置类型,或者元组,字符串安全
phonebook={'alice': '2341', 'beth':'9102'} 函数
键值对列表作参数学习
>>> items=[("name", "Gumby"), ("age", 42)] >>> dict(items) {'age': 42, 'name': 'Gumby'}
键值对参数spa
>>> d = dict(name="Gumby", age=42) >>> d {'age': 42, 'name': 'Gumby'}
基本字典操做code
格式化字符串 %(key)type索引
>>> phonebook={"beth":"9102", "alice":"2341"} >>> print "%(beth)s" % phonebook 9102 >>>
>>> x={"username":"admin", "machines":["foo", "bar", "baz"]} >>> x {'username': 'admin', 'machines': ['foo', 'bar', 'baz']} >>> y=x.copy() >>> y {'username': 'admin', 'machines': ['foo', 'bar', 'baz']} >>> y["username"]="mlh" >>> y["machines"].remove("bar") >>> y {'username': 'mlh', 'machines': ['foo', 'baz']} >>> x {'username': 'admin', 'machines': ['foo', 'baz']} >>> import copy >>> z=copy.deepcopy(x) >>> z {'username': 'admin', 'machines': ['foo', 'baz']} >>> z["machines"].remove("foo") >>> z {'username': 'admin', 'machines': ['baz']} >>> x {'username': 'admin', 'machines': ['foo', 'baz']} >>>
fromkeys:使用给定的key创建新字典,每一个key对应的默认值为Nonerem
>>> {}.fromkeys(["name", "age"]) {'age': None, 'name': None} >>> >>> dict.fromkeys(["name", "age"], "(unkonwn)") {'age': '(unkonwn)', 'name': '(unkonwn)'} >>>
get 安全访问字典,当key不存在的时候返回None字符串
>>> a={} >>> a['a'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'a' >>> print a.get("a") None >>>
has_key 返回key是否存在get
items和iteritems,以列表形式返回字典中的项,列表中的元素为字典中的项,iteritems会返回一个迭代器
keys和iterkeys,以列表形式返回字典中key
pop,获取给定key的值,而后从字典中移除
popitem,弹出一个项
setdefault,获取给定key的值,若是没有则设置并返回默认值
update 参数字典中项会被添加到旧字典中,如有相同的key则进行覆盖
values和itervalues 以列表的形式返回字典中值