Python字典

一个简单的字典

alien = {'color':'green', 'points':5}

或者

alien = {

    'color':'green',

    'points':5, # 这个逗号可加可不加

    }

print(alien)

print(alien['color'])

print(alien['points'])

字典定义

在Python中,字典是一系列键-值对。每个键都与一个值相关联,可以使用键来访问相关的值。值可以是数字、字符串、列表乃至字典,可以将Python中任何对象用作字典中的值。

创建字典

alien = {}

alien = dict()

初始化字典

alien = { 'color':'green' }

alien = dict(color='green')   # 更优雅

alien = {}.fromkeys(['color', 'points'])   # 此时的内容为 { 'color': None, 'points': None }

alien = dict().fromkeys(['color', 'points']) # 同上

添加键-值对

字典是一种动态结构,可随时在其中添加键-值对。对上面的字典进行添加:

alien['position'] = 100

注意:添加顺序和排列顺序可能不同,Python不关心添加顺序

获取键值

alien['color']  # 返回green

alien.get('color') # 返回green

alien.get('colour') # 返回None

alien.get('colour','yellow') # 返回yellow # 要么第一个,要么第二个

alien.values() # 返回所有值

alien.items()  # 返回键值对

获取键

alien.keys() # 返回所有键

判断一个键是否已存在

用 in 或 not in , 例如 'colour' in alien.keys() 返回False 或者 'color' in alien 返回True

Python 3.X 里不包含 has_key() 函数,被 __contains__(key) 替代

获取最大的Value的键

max(dict,key=dict.get)

该方法首先遍历迭代器,并将返回值作为参数传递给key对应的函数,然后将函数的执行结果传给key,并以此时key值为标准进行大小判断,返回最大值

删除键-值对

del alien['points'] # 删除键值对

alien.pop('color')  # 删除color键值对,并返回值

alien.clear() # 删除所有键值对

判断非空

if alien:

    pass # 如果是空的,则返回 False. 

False,0,'',[],{},()都可以视为假

遍历字典

可以遍历键值对、键、值

遍历所有的键-值对

alien = {'color': 'green', 'points': 5}

for key, value in alien.items():

    print("\nKey: ", key)

    print("Value: ", value)

遍历字典中的所有键

在不需要使用字典中的值时,方法 keys() 很有用

alien = {'color': 'green', 'points': 5}

for key in alien.keys():

    print("Key: ", key)

由于遍历字典时,会默认遍历所有的键,所以上述代码也可以写成 for key in alien:

但是显式地写出来可让代码更容易理解

按顺序遍历字典中的所有键

字典总是记录关联关系,但是获取字典元素的时候,获取顺序确实不可预测的,要以特定顺序返回元素,一种方法是在for循环中对返回的键进行排序,可使用sorted()来获取副本:

for key in sorted(alien.keys()):

遍历字典中的所有值

如果只对值感兴趣,可以使用 values() 方法,它返回一个值列表,比如:

for value in alien.values():

这种方法不会去重,如果包含大量重复项,则应该使用集合set,集合 类似于列表,但是无重复项。例如:

for value in set(alien.values()):

原文档

len(d)  返回字典d的长度

d[key]  返回d[key]的值,若没有则raise a KeyError

d[key] = value 给d[key]重新赋值

del d[key]  删除d[key], 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  等价于 not key in d.

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

clear()  删除该字典的所有值

copy()    返回一个字典的浅拷贝

classmethod fromkeys(iterable[, value])   Create a new dictionary with keys from iterable and values set to value.

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

get(key[, default]) 返回字典中key的值,否则返回第二个参数,第二个参数默认为None

items()    Return a new view of the dictionary's items ((key, value) pairs). See the documentation of view objects.

keys()     Return a new view of the dictionary's keys. See the documentation of view objects.

pop(key[, default]) 删除指定给定键所对应的值,返回这个值并从字典中把它移除,否则返回 default

popitem()    Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order.

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.

在 3.7 版更改: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair.

setdefault(key[, default])  如果字典存在键 key ,返回它的值。如果不存在,插入值为 default 的键 key ,并返回 default 。 default默认为 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).

values()   Return a new view of the dictionary's values. See the documentation of view objects.

两字典只有键值对都相等的时候才相等,不能用<,>,<=,>=来比较

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}

在 3.7 版更改: 字典保持插入的顺序。Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值