赛博红兔的科技博客

CyberHongTu shares news, insights, and musings on fascinating technology subjects.


和我一起玩Python:12. 字典

今天,咱们聊聊Python里的字典。定义字典,可以用dict()函数或者直接用大括号{},里面是一堆键值对,每个键都得是独一无二的。比如说,想弄个字典存一个人的名字、年龄和他是不是新来的,可以这么写:”my_dict = {‘name’: ‘HongTu’, ‘age’: 16, ‘is_new’: True}”。用键可以找到对应的值,但如果这键字典里没得,那就会报错。为了避免这个,可以用get()方法,这样找不到键就会返回个None,不会报错了。改字典里的值也简单,直接给键分配个新值就行。还有个update()方法,可以一次性改好几个值。想看字典里有啥键、值或者是键值对,就用keys(), values(), 和items()这几个方法,挺方便的。

Dictionary Method List

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary’s keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

字典方法列表

方法描述
clear()删除字典中的所有元素
copy()返回字典的副本
fromkeys()返回具有指定键和值的字典
get()返回指定键的值
items()返回一个列表,其中包含每个键值对的元组
keys()返回一个列表,其中包含字典的键
pop()删除具有指定键的元素
popitem()删除最后插入的键值对
setdefault()返回指定键的值。如果键不存在:插入具有指定值的键
update()使用指定的键值对更新字典
values()返回字典中所有值的列表


Leave a comment