python学习笔记整理

数据结构——字典

无序的 {键:值} 对集合

用于查询的方法

len(d)

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.

If a subclass of dict defines a method _missing_() and key is not present, the d[key] operation

calls that method with the key key as argument. The d[key] operation then returns or raises what-

ever is returned or raised by the missing(key) call. No other operations or methods invoke

missing() 继承dict()后可自定义的固有类方法

  • 自定义字典找不到元素时引发的事件方法

If missing() is not defined, KeyError is raised. missing() must

be a method; it cannot be an instance variable:

>>> class Counter(dict):

... def missing(self, key):

... return 0

>>> c = Counter()

>>> c['red']

0

>>> c['red'] += 1

>>> c['red']

1

The example above shows part of the implementation of collections.Counter. A different

_missing_ method is used by collections.defaultdict.

New in version 2.5: Recognition of _missing_ methods of dict subclasses.

key in d

Return True if d has a key key, else False.

key not in d

Equivalent to not key in 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.

has_key(key)

Test for the presence of key in the dictionary. has_key() is deprecated in favor of key in d.

赋值

    字典生成
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

d[key] = value

  • 置数赋值

Set d[key] to value.

fromkeys(seq [ , value ] )

Create a new dictionary with keys from seq and values set to value.

c=a.fromkeys(['one'])

fromkeys() is a class method that returns a new dictionary. value defaults to None.

操作

del d[key]

  • 根据键值移除

Remove d[key] from d. Raises a KeyError if key is not in the map.

clear()

  • 清空

    Remove all items from the dictionary.

调用

iter(d)

Return an iterator over the keys of the dictionary. This is a shortcut for iterkeys().

copy()

Return a shallow copy of the dictionary.

>>>举例

>>> a.items()

[('three', 3), ('two', 2), ('one', 1)]

>>> iter(a)

<dictionary-keyiterator object at 0x024FF8A0>

>>> for i in iter(a):

... print i

...

three

two

one

items()

Return a copy of the dictionary’s list of (key, value) pairs.

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random,

varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called

with no intervening modifications to the dictionary, the lists will directly correspond.

This allows the creation of (value, key) pairs using zip():

pairs = zip(d.values(), d.keys()).

The same relationship holds for the iterkeys() and itervalues() methods:

pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs.

Another way to create the same list is

pairs = [(v, k) for (k, v) in d.iteritems()

iteritems()

Return an iterator over the dictionary’s (key, value) pairs. See the note for dict.items().

Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or

fail to iterate over all entries.

iterkeys()

Return an iterator over the dictionary’s keys. See the note for dict.items().

Using iterkeys() while adding or deleting entries in the dictionary may raise a RuntimeError or

fail to iterate over all entries.

New in version 2.2.

itervalues()

Return an iterator over the dictionary’s values. See the note for dict.items().

Using itervalues() while adding or deleting entries in the dictionary may raise a RuntimeError

or fail to iterate over all entries.

keys()

Return a copy of the dictionary’s list of keys. See the note for dict.items().

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.

popitem()

Remove and return an arbitrary (key, value) pair from the dictionary.

popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the

dictionary is empty, calling popitem() raises a KeyError.

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.

update( [ other ] )

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).

Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword

arguments.

values()

Return a copy of the dictionary’s list of values. See the note for dict.items().

viewitems()

Return a new view of the dictionary’s items ((key, value) pairs). See below for documentation of

view objects.

New in version 2.7.

viewkeys()

Return a new view of the dictionary’s keys. See below for documentation of view objects.

New in version 2.7.

viewvalues()

Return a new view of the dictionary’s values. See below for documentation of view objects.

New in version 2.7.

Dictionaries compare equal if and only if they have the same (key, value) pairs.

参考python2.7文档

  • 抓紧时间睡个觉

python学习笔记整理——字典的更多相关文章

  1. python学习笔记整理——集合 set

    python学习整理笔记--集合 set 集合的用途:成员测试和消除重复的条目,进行集合运算 注意:花括号或set()函数可以用于创建集合. 注意:若要创建一个空的集合你必须使用set(),不能用{} ...

  2. python学习笔记整理——列表

    Python 文档学习笔记 数据结构--列表 列表的方法 添加 list.append(x) 添加元素 添加一个元素到列表的末尾:相当于a[len(a):] = [x] list.extend(L) ...

  3. python学习笔记整理——元组tuple

    Python 文档学习笔记2 数据结构--元组和序列 元组 元组在输出时总是有括号的 元组输入时可能没有括号 元组是不可变的 通过分拆(参阅本节后面的内容)或索引访问(如果是namedtuples,甚 ...

  4. python 学习笔记整理

    首先自我批评一下,说好的一天写一篇博客,结果不到两天,就没有坚持了,发现自己做什么事情都没有毅力啊!不能持之以恒.但是,这次一定要从写博客开始来改掉自己的一个坏习惯. 可是写博客又该写点什么呢? 反正 ...

  5. Python学习笔记整理总结【语言基础篇】

    一.变量赋值及命名规则① 声明一个变量及赋值 #!/usr/bin/env python # -*- coding:utf-8 -*- # _author_soloLi name1="sol ...

  6. Python学习笔记之字典

    一.创建和使用字典 1.创建字典 phonebook={'Alice':'2341','Beth':'9102','Cecil':'3258'} 2.dict,通过映射创建字典 >>> ...

  7. 【Python学习笔记】字典操作

    字典dict是Python中唯一内置的映射类型,由键值对组成,字典是无序的.字典的键必须是不变对象,如字符串.数字.元组等,而包含可变对象的列表.字典和元组则不能作为键.这里可变和不可变的意思是指这个 ...

  8. Python学习笔记四--字典与集合

    字典是Python中唯一的映射类型.所谓映射即指该数据类型包含哈希值(key)和与之对应的值(value)的序列.字典是可变类型.字典中的数据是无序排列的. 4.1.1字典的创建及赋值 dict1={ ...

  9. Python学习笔记整理(十)Python的if测试

    if语句是选取要执行的操作. 一.if语句 1.通用格式 形式是if测试,后面跟着一个或多个可选的elif(else if)测试,以及一个最终选用的else块.测试和else部分可以结合嵌套语句块,缩 ...

随机推荐

  1. shell编程入门

    背景知识 Shell 是用户与内核进行交互操作的一种接口,是 Linux 最重要的软件之一.目前最流行的 Shell 称为 bash Shell,bash Shell 脚本编程以其简洁.高效而著称,多 ...

  2. ASP.NET Web API 安全筛选器

    原文:https://msdn.microsoft.com/zh-cn/magazine/dn781361.aspx 身份验证和授权是应用程序安全的基础.身份验证通过验证提供的凭据来确定用户身份,而授 ...

  3. 【分享】4412开发板ubuntu 12.0.4播放音乐没有声音解决方法

    转自迅为论坛:http://bbs.topeetboard.com 准备工作 1.下载 vim 在命令行上输入 apt-get install vim 下载 vim 2.输入 vim /etc/hos ...

  4. JavaWeb学习----Cookie实现记住密码的功能

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  5. 大话设计模式C++版——工厂方法模式

    工厂方法模式是以简单工厂模式为基础的,如果未了解简单工厂模式的同学可先浏览<大话设计模式C++版——简单工厂模式>.在简单工厂模式中,提到过简单工厂模式的缺陷,即违背了开发—封闭原则,其主 ...

  6. 怎样运用好ZBrush中的布尔运算

     我们知道DynaMesh常用于基础模型的起稿到中模的制作,它是ZBrush ® 4R2新增的功能,其强大的功能除了对模型进行重新布线,还可以进行布尔运算.配合Insert笔刷进行布尔运算,可以做出Z ...

  7. 扫盲 BT Sync——不仅是同步利器,而且是【分布式】网盘

    先向大伙儿宣布个好消息-- 经过多位热心读者的大力支持,经过几天的努力,已经完成了"微软网盘"到"BitTorrent Sync"的迁移工作. 再次向这批热心读 ...

  8. js获取鼠标位置的各种方法

    在一些DOM操作中我们经常会跟元素的位置打交道,鼠标交互式一个经常用到的方面,令人失望的是不同的浏览器下会有不同的结果甚至是有的浏览器下没结果,这篇文章就上鼠标点击位置坐标获取做一些简单的总结,没特殊 ...

  9. 洛谷P1120小木棍[DFS]

    题目描述 乔治有一些同样长的小木棍,他把这些木棍随意砍成几段,直到每段的长都不超过50. 现在,他想把小木棍拼接成原来的样子,但是却忘记了自己开始时有多少根木棍和它们的长度. 给出每段小木棍的长度,编 ...

  10. jsp前三章小测试:错题

    /bin:存放各种平台下用于启动和停止Tomcat的脚本文件 /logs:存放Tomcat的日志文件 /webapps:web应用的发布目录 /work:Tomcat把由JSP生成的Servlet存放 ...