美文网首页
Python中创建字典的几种方法

Python中创建字典的几种方法

作者: caoxinyiyi | 来源:发表于2018-07-23 11:26 被阅读5次
    1.传统的文字表达式:
    >>> d={'name':'Allen','age':21,'gender':'male'}
    >>> d
    {'gender': 'male', 'age': 21, 'name': 'Allen'}
    

    如果你可以事先拼出整个字典,这种方式是很方便的。

    2.动态分配键值:
    >>> d ={}
    >>> d['name'] = 'Allen'
    >>> d
    {'name': 'Allen'}
    

    如果你需要一次动态地建立一个字典的一个字段,那么这种方式比较合适。

    3.字典键值表
    >>> c = dict(name='Allen', age=14, gender='male')
    >>> c
    {'gender': 'male', 'age': 14, 'name': 'Allen'}
    

    因为这种形式语法简单,不易出错,所以非常流行。

    这种形式所需的代码比常量少,但是键必须都是字符串才行,所以下列代码会报错:

    >>> c = dict(name='Allen', age=14, gender='male', 1='abcd')
      File "<stdin>", line 1
    SyntaxError: keyword can't be an expression
    
    4.字典键值元组表
    >>> e=dict([('name','Allen'),('age',21),('gender','male')])
    >>>
    >>>
    >>> e
    {'gender': 'male', 'age': 21, 'name': 'Allen'}
    

    如果你需要在程序运行时把键和值逐步建成序列,那么这种方式比较有用。

    5.所有键的值都相同或者赋予初始值:
    >>> f=dict.fromkeys(['height','weight'],'normal')
    >>> f
    {'weight': 'normal', 'height': 'normal'}
    

    相关文章

      网友评论

          本文标题:Python中创建字典的几种方法

          本文链接:https://www.haomeiwen.com/subject/heidmftx.html