Python学习笔记-字典

2018-04-26  本文已影响0人  睡觉谁叫

1. Python中字典相关基本概念

字典.png

2. get(key,default)与setdefault(key,default)的区别?

get与setdefault区别.png
>>> spam = {'a' : 1 , 'b' : 2}
>>> spam.get('c')
>>> spam.get('c',3)
3
>>> spam
{'a': 1, 'b': 2}
>>> spam.setdefault('c',4)
4
>>> spam
{'a': 1, 'c': 4, 'b': 2}
>>> spam.setdefault('c',5)
4
>>> spam
{'a': 1, 'c': 4, 'b': 2}
>>>

3.字典增删操作

增删操作.png
增加操作示例代码
>>> samp = {}
>>> type(samp)
<type 'dict'>
>>> samp['a'] = 0
>>> samp
{'a': 0}
>>> samp.setdefault('b',1)
1
>>> samp
{'a': 0, 'b': 1}
>>> samp.get('c',2)
2
>>> samp
{'a': 0, 'b': 1}
>>>
删除操作示例代码
  1. 删除键值对
>>> samp
{'a': 0, 'b': 1}
>>> del samp['a']
>>> samp
{'b': 1}
>>> samp.setdefault('a',9)
9
>>> samp
{'a': 9, 'b': 1}
>>> samp.pop('a')
9
>>> samp
{'b': 1}
>>>
>>>
  1. 清空字典
>>> samp
{'b': 1}
>>> samp.clear()
>>> samp
{}
  1. 删除字典对象
>>> samp['a'] = 1
>>> samp['b'] = 2
>>> samp
{'a': 1, 'b': 2}
>>> del samp
>>> samp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'samp' is not defined
>>>

4. Python常见报错收集

  1. 报错日志: SyntaxError: Missing parentheses in call to 'print'. Did you mean print(int 'Inventory:')?
    报错原因: print 方法没有带上括号
    错误示例: print 'abc'
    正确示例: print ('abc')
  1. 报错日志: ValueError: too many values to unpack (expected 2)
    报错原因:字典多重赋值用法错误
    错误示例: for k, v in dict
    正确示例:for k,v in dict.items()
  1. 报错日志: TypeError: must be str, not int
    报错原因:整形没有转化成字符串
    错误示例:print (key + " :" + v)
    正确示例:print (key + " :" + str(v))
上一篇下一篇

猜你喜欢

热点阅读