python学习笔记整理——字典

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文档

  • 抓紧时间睡个觉
原文地址:https://www.cnblogs.com/learn-to-rock/p/5315111.html