示例示例Python字典常用方法有:dict.clear():清空字典中的所有元素,示例代码如下:
Python字典常用方法有:
1. dict.clear():清空字典中的所有元素,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
dict.clear()
print(dict)
# 输出:{}
2. dict.copy():返回一个字典的浅复制,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
dict_copy = dict.copy()
print(dict_copy)
# 输出:{'name': 'John', 'age': 24}
3. dict.fromkeys(seq[, value]):创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值,示例代码如下:
python
seq = ('name', 'age')
dict = dict.fromkeys(seq)
print(dict)
# 输出:{'name': None, 'age': None}
4. dict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
print(dict.get('name'))
# 输出:John
print(dict.get('', 'unknown'))
# 输出:unknown
5. dict.items():以列表返回可遍历的(键, 值)元组数组,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
print(dict.items())
# 输出:dict_items([('name', 'John'), ('age', 24)])
6. dict.keys():返回一个迭代器,可以使用 list() 来转换为列表,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
print(list(dict.keys()))
# 输出:['name', 'age']
7. dict.pop(key[, default]):删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值,示例代码如下:
python
dict = {'name': 'John', 'age': 24}
print(dict.pop('name'))
# 输出:John
8. dict.popitem():随机返回并删除字典中的一对键和值,示例
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(46条)