字典

2017-10-10  本文已影响0人  小浣熊嘎嘣脆

创建字典

char = {'a':'first','b':'second','c':'third'}  #键必须是独一无二,但值不必
print(char)
{'a': 'first', 'b': 'second', 'c': 'third'}

访问字典中的值

char = {'a':'first','b':'second','c':'third'}
print(char['b'])
second

修改、添加字典

修改字典中的值

char = {'a':'first','b':'second','c':'third'}
char['c']='no third'
print(char)
{'a': 'first', 'b': 'second', 'c': 'no third'}

在末尾增添新的键/值

char = {'a':'first','b':'second','c':'third'}
char['d'] = 'fouth'
print(char)
{'a': 'first', 'b': 'second', 'c': 'third', 'd': 'fouth'}

删除字典元素

char = {'a':'first','b':'second','c':'third'}
del char['c']
print(char)
{'a': 'first', 'b': 'second'}

删除字典

char = {'a':'first','b':'second','c':'third'}
del char
print(char)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-21-1222cadc5af4> in <module>()
      1 char = {'a':'first','b':'second','c':'third'}
      2 del char
----> 3 print(char)


NameError: name 'char' is not defined

清空字典

char = {'a':'first','b':'second','c':'third'}
char.clear()
print(char)
{}

Python字典包含了以下内置函数:

  1. cmp(dict1, dict2):比较两个字典元素。
  2. len(dict):计算字典元素个数,即键的总数。
  3. str(dict):输出字典可打印的字符串表示。
  4. type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:

  1. radiansdict.clear():删除字典内所有元素
  2. radiansdict.copy():返回一个字典的浅复制
  3. radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
  4. radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
  5. radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
  6. radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
  7. radiansdict.keys():以列表返回一个字典所有的键
  8. radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
  9. radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
  10. radiansdict.values():以列表返回字典中的所有值
上一篇 下一篇

猜你喜欢

热点阅读