字典及字典方法實例

字典

字典是python中的惟一的映射類型(哈希表)python

字典對象是可變的,可是字典的鍵必須使用不可變對象,一個字典中可使用不一樣類型的鍵值。.net

字典的方法

    keys()orm

    values()對象

    items()ip

舉例以下:get

    In [10]: dic = {}input

    In [11]: type(dic)hash

    Out[11]: dictit

    In [12]: dic = {'a':1,1:123}for循環

    In [13]: dic

    Out[13]: {1: 123, 'a': 1}

    In [14]: dic = {'a':1,1:123,('a','b'):'hello'}

    In [15]: dic = {'a':1,1:123,('a','b'):'hello',[1]:1}

    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <ipython-input-15-4fc52e86cb96> in <module>()

    ----> 1 dic = {'a':1,1:123,('a','b'):'hello',[1]:1}

    TypeError: unhashable type: 'list'

    In [16]: len(dic)

    Out[16]: 3

    In [17]: dic.keys()

    Out[17]: ['a', 1, ('a', 'b')]

    In [18]: dic.values()

    Out[18]: [1, 123, 'hello']

    In [19]: dic.get('a')

    Out[19]: 1

    In [20]: dic

    Out[20]: {1: 123, 'a': 1, ('a', 'b'): 'hello'}

    In [21]: dic[1]

    Out[21]: 123

更改字典內value:

    In [22]: dic['a'] = 2

    In [23]: dic

    Out[23]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

查看是否是在字典裏

    In [28]: 'b' in dic

    Out[28]: False

    In [29]: 'a' in dic

    Out[29]: True

    In [30]: dic.has_key('a')

    Out[30]: True

    In [31]: dic.has_key('b')

    Out[31]: False

變爲列表:

    In [32]: dic.items()

    Out[32]: [('a', 2), (1, 123), (('a', 'b'), 'hello')]

    In [33]: dic

    Out[33]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

複製字典:

    In [34]: dic1 = dic.copy()

    In [35]: dic1

    Out[35]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

    In [36]: dic

    Out[36]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

刪除字典內容:

    In [37]: dic.pop(1)

    Out[37]: 123

    In [38]: dic

    Out[38]: {'a': 2, ('a', 'b'): 'hello'}

    In [39]: dic.pop(2)

    ---------------------------------------------------------------------------

    KeyError                                  Traceback (most recent call last)

    <ipython-input-39-9f97239cddce> in <module>()

    ----> 1 dic.pop(2)

    KeyError: 2

    In [40]:

更新字典,兩個字典更新爲一個:

    In [40]: dic1 = {1:1,2:2}

    In [41]: dic.update(dic1)

    In [42]: dic1

    Out[42]: {1: 1, 2: 2}

    In [43]: dic

    Out[43]: {1: 1, 2: 2, 'a': 2, ('a', 'b'): 'hello'}

建立字典:

    dic = {}

    dic = dict()

    help(dict)

    dict((['a',1],['b',2]))

    dict(a=1,b=2)

    fromkeys(),字典元素有相同的值時,默認爲None.

    ddict = {}.formkeys(('x','y'),100)

    dic.fromkeys(range(100),100)

    In [45]: dic.fromkeys('abc')

    Out[45]: {'a': None, 'b': None, 'c': None}

    In [42]: dic = {}

    In [43]: dic

    Out[43]: {}

    In [44]: dict()

    Out[44]: {}

    In [45]: dict(x=10,y=100)

    Out[45]: {'x': 10, 'y': 100}

    In [46]: dict([('a',10),('b',20)])

    Out[46]: {'a': 10, 'b': 20}

訪問字典:

    In [10]: dic={1:1,2:3,3:5}

    In [11]: dic

    Out[11]: {1: 1, 2: 3, 3: 5}

    In [12]: dic[2]

    Out[12]: 3

    In [13]: dic.items()

    Out[13]: [(1, 1), (2, 3), (3, 5)]

for循環訪問:

    In [15]: for i in dic:

    ....:     print i,dic[i]

    ....:

    1 1

    2 3

    3 5

     In [18]: for i in dic:

    ....:     print "%s,%s" % (i,dic[i])

    ....:

    1,1

    2,3

    3,5

    In [19]: dic

    Out[19]: {1: 1, 2: 3, 3: 5}

    In [19]: dic

    Out[19]: {1: 1, 2: 3, 3: 5}

    In [21]: for k,v in dic.items():print k,v

    1 1

    2 3

    3 5

字典練習

    寫出腳本,根據提示輸入內容,並輸入到字典中。

1種:

    [root@localhost python]# cat dict.py

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    print info

    [root@localhost python]#

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:20

    Please input (M/F):M

    {'gender': 'M', 'age': '20', 'name': 'fxq'}

    [root@localhost python]#

2.種

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    print info.items()

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    [('gender', 'M'), ('age', '22'), ('name', 'fxq')]

    [root@localhost python]#

3.種

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for i in info.items():

        print i

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    ('gender', 'M')

    ('age', '22')

    ('name', 'fxq')

    main end

    [root@localhost python]#

4.種

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print k,v

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    gender M

    age 22

    name fxq

    main end

    [root@localhost python]#

5.種

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print "%s:%s" % (k,v)

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22    

    Please input (M/F):M

    gender:M

    age:22

    name:fxq

    main end

    [root@localhost python]#

6.種

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print "%s" % k

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    gender

    age

    name

    main end

    [root@localhost python]#

相關文章
相關標籤/搜索