python创建字典的三种方式


创建空字典:

    dict_eq={}
    print(type(dict))

直接赋值创建字典:

    dict_eq={'a':1,'b':2,'c':'adbc'}

通过关键字dict和关键字参数创建

    dict_eq=dict(spam = 1, egg = 2, bar =3)

通过二元组列表创建

    >>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
    >>> dic = dict(list)

dict和zip结合创建

    dic = dict(zip('abc', [1, 2, 3]))

通过字典推导式创建

    >>> dic = {i:2*i for i in range(3)}
    >>> dic
    >>> {0: 0, 1: 2, 2: 4}

通过dict.fromkeys()创建

>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM