Python字典dict的常用方法和函数

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

  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. 字典的遍历,遍历值
    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])
  12. 字典的遍历

猜你喜欢

转载自blog.51cto.com/xxy12345/2544446