|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
字典对象的所有除魔法方法外的函数有: ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
#########################
1. clear()
清空字典- >>> test = {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test
- {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test.clear()
- >>> test
- {}
复制代码
2. copy()
复制字典- >>> raw = {1: 'i', 2: 'love', 3: 'fishc'}
- >>> same = raw.copy()
- >>> raw
- {1: 'i', 2: 'love', 3: 'fishc'}
- >>> same
- {1: 'i', 2: 'love', 3: 'fishc'}
- >>> id(same) == id(raw)
- False
复制代码
3. fromkeys(iterable, value)
返回一个字典, 键为iterable里的每一项, 值为value, 等效于 {i: value for i in iterable}- >>> {}.fromkeys(range(1, 33), 'Excellent')
- {1: 'Excellent', 2: 'Excellent', 3: 'Excellent', 4: 'Excellent', 5: 'Excellent', 6: 'Excellent', 7: 'Excellent', 8: 'Excellent', 9: 'Excellent', 10: 'Excellent', 11: 'Excellent', 12: 'Excellent', 13: 'Excellent', 14: 'Excellent', 15: 'Excellent', 16: 'Excellent', 17: 'Excellent', 18: 'Excellent', 19: 'Excellent', 20: 'Excellent', 21: 'Excellent', 22: 'Excellent', 23: 'Excellent', 24: 'Excellent', 25: 'Excellent', 26: 'Excellent', 27: 'Excellent', 28: 'Excellent', 29: 'Excellent', 30: 'Excellent', 31: 'Excellent', 32: 'Excellent'}
复制代码
4. get(k[, d])
返回字典中键k对应的值, 如果字典中没有键k, 则返回d- >>> test = {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test.get(3, 'key不存在!)
- 'fishc'
- >>> test.get('ddd', 'key不存在!)
- 'key不存在!'
复制代码
5. keys(), values(), items()
keys()返回字典中所有键的列表
values()返回字典所有值的列表
items()返回字典(键, 值)的列表- >>> test = {'aac': ('777', 6), 66: 'love', 45: 765, 'hh': 'fishc'}
- >>> test.keys()
- dict_keys(['aac', 66, 45, 'hh'])
- >>> test.values()
- dict_values([('777', 6), 'love', 765, 'fishc'])
- >>> dict.items()
- dict_items([('aac', ('777', 6)), (66, 'love'), (45, 765), ('hh', 'fishc')])
复制代码
6. pop(k[, d])
返回字典中k对应的值, 并删除, 不存在就返回d- >>> test = {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test
- {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test.pop(1, '不存在!')
- 'i'
- >>> test
- {2: 'love', 3: 'fishc'}
- >>> test.pop(1, '不存在!')
- '不存在!'
- >>> test
- {2: 'love', 3: 'fishc'}
复制代码
7. popitem()
返回字典中的第一项(默认顺序), 并从字典中删除- >>> test = {1: 'i', 2: 'love', 3: 'fishc'}
- >>> test.popitem()
- (1, 'i')
- >>> test
- {2: 'love', 3: 'fishc'}
复制代码
8. setdefault(k[, d])
如果键在字典中, 返回这个键所对应的值
如果键不在字典中, 向字典中加入这个键, 以d为这个键的值, 并返回d- >>> test = {2: 'love', 3: 'fishc'}
- >>> test
- {2: 'love', 3: 'fishc'}
- >>> test.setdefault(2, '!!!!!')
- 'love'
- >>> test
- {2: 'love', 3: 'fishc'}
- >>> test.setdefault(1, 'i')
- 'i'
- >>> test
- {1, 'i', 2: 'love', 3: 'fishc'}
复制代码
9. update
将新字典添加到原字典- >>> raw = {1: 'i', 4: 'com'}
- >>> add = {2: 'love', 3: 'fishc'}
- >>> raw
- {1: 'i', 4: '.com'}
- >>> raw.update(add)
- >>> raw
- {1: 'i', 2: 'love', 3: 'fishc', 4: '.com'}
复制代码 |
评分
-
查看全部评分
|