当前位置:   article > 正文

python创建字典的6种方式_create dictionary用法

create dictionary用法

方式一:

  1. >>> dict1={}
  2. >>> dict1['firstname']='ma'
  3. >>> dict1['lastname']='yun'
  4. >>> dict1
  5. {'firstname': 'ma', 'lastname': 'yun'}

方式二:

  1. >>> dict1 = {'firstname':'ma', 'lastname':'yun'}
  2. >>> dict1
  3. {'firstname': 'ma', 'lastname': 'yun'}

方式三:

  1. >>> dict1=dict(firstname='ma',lastname='yun') #传入关键字(键值对)
  2. >>> dict1
  3. {'firstname': 'ma', 'lastname': 'yun'}

方式四:

  1. >>> dict1=dict([('firstname','ma'),('lastname','yun')]) #传入可迭代对象(此处为list)
  2. >>> dict1
  3. {'firstname': 'ma', 'lastname': 'yun'}
  4. >>>

方式五:

  1. >>> dict1=dict((['firstname','ma'],['lastname','yun'])) #传入可迭代对象(此处为tuple)
  2. >>> dict1
  3. {'firstname': 'ma', 'lastname': 'yun'}

方式六:

  1. >>> dict1=dict(zip(['firstname','lastname'],['ma','yun'])) #通过zip()映射函数构造
  2. >>> dict1
  3. {'firstname': 'ma', 'lastname': 'yun'}

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/714368
推荐阅读
相关标签
  

闽ICP备14008679号