Python字典dict的經常使用方法和函數

dict={'name':'Joe','age':18,'height':60}ide

  1. clear,清空
    dict.clear()
    #運行結果{}
  2. pop,移除指定key的鍵值對並返回vlaue(若是沒有該key,可返回指定值),popitem,默認移除最後一個鍵值對
    print(dict.pop('age'))
    print(dict)
    #結果18,{'name': 'Joe', 'height': 60}
    print(dict.pop('agea','erro'))
    print(dict)
    #結果erro,{'name': 'Joe', 'age': 18, 'height': 60}
    print(dict.popitem())
    print(dict)
    #結果('height', 60),{'name': 'Joe', 'age': 18}
  3. del,刪除字典的另外一種方式
    del dict['age']
    print(dict)
    #結果{'name': 'Joe', 'height': 60}
  4. get,返回指定鍵的值,若是值不在字典中返回default值,等同於dict.__getitem__('name')
    print(dict.get('name'))
    #結果Joe
    print(dict.get('hobby'))
    #結果None
    print(dict.get('hobby','basketball'))
    #結果basketball
  5. setdefault,和get()相似, 但若是鍵不存在於字典中,將會添加鍵並將值設爲default
    print(dict.setdefault('hobby'))
    print(dict)
    #結果None,{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': None}
    print(dict.setdefault('hobby','basketball'))
    print(dict)
    #結果basketball,{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': 'basketball'}
  6. update,更新字典,有key則更新該key對應的vlaue,沒有則新增
    dict.update({'age':20})
    print(dict)
    #結果{'name': 'Joe', 'age': 20, 'height': 60}
    dict.update({'hobby':'run'})
    print(dict)
    #結果{'name': 'Joe', 'age': 18, 'height': 60, 'hobby': 'run'}
  7. fromkeys,建立新字典,以seq爲key,vlaue爲字典的初始值
    seq = ('a', 'b', 'c')
    print(dict.fromkeys(seq))
    #結果{'a': None, 'b': None, 'c': None}
    print(dict.fromkeys(seq,'oh'))
    #結果{'a': 'oh', 'b': 'oh', 'c': 'oh'}
  8. 字典的打印,取值等
    print(dict.items())
    print(dict.values())
    print(dict.keys())
    #結果
    dict_items([('name', 'Joe'), ('age', 18), ('height', 60)])
    dict_values(['Joe', 18, 60])
    dict_keys(['name', 'age', 'height'])
  9. 字典的遍歷,遍歷key
    for i in dict:
    print(i)
    #結果
    name
    age
    height
    #相同效果的遍歷以下:
    for key in dict.keys():
    print(key)
    #
  10. 字典的遍歷,遍歷value
    for vlaue in dict.values():
    print(vlaue)
    #結果
    Joe
    18
    60
  11. 字典的遍歷,遍歷item
    #10.1輸出爲元組的方式
    for item in dict.items():
    print(item)
    #結果
    ('name', 'Joe')
    ('age', 18)
    ('height', 60)
    #10.2輸出爲字符串的方式
    for key,vlaue in dict.items():
    print(key,vlaue)
    #結果
    name Joe
    age 18
    height 60
    #輸出爲字符串的另外一種方式
    for i in dict:
    print(i,dict[i])
相關文章
相關標籤/搜索