【Python基础】之字典dict

川长思鸟来 2022-02-19 05:21 513阅读 0赞

字典用{}包含元素,每个元素为一个键值对(key,value)

1.字典的初始化,打印出字典中的键,值

dic = {}

dic = dict()

  1. dic = {1:'one', 2:'two',3:'three',4:'four'}
  2. for i in dic:
  3. print(i) #输出键1 2 3 4
  4. for i in dic.keys():
  5. print(i)#输出键1 2 3 4
  6. for i in dic.values():
  7. print(i)#输出值one two three four

2.字典的常用功能:

  • keys():获取字典中所有的键,并返回一个列表
  • value():获取字典中所有的值,并返回一个列表
  • items():获取字典中的所有键值对

    dic = {1:’one’, 2:’two’,3:’three’,4:’four’}
    for k,v in dic.items():

    1. print(k,v)
  • get():根据键获取值,若key不存在,返回None;如果直接按照索引取值,key不存在时会报错,因此若要取值,建议用get()

  • clear():清楚字典
  • update():传入参数为一个字典,更新原字典,举例如下

    dic = {1:’one’, 2:’two’,3:’three’,4:’four’}
    dic2 = {1:’one1’,5:’five’,3:’three’}
    dic.update(dic2)
    print(dic)#输出:{1: ‘one1’, 2: ‘two’, 3: ‘three’, 4: ‘four’, 5: ‘five’}

  • pop():根据key,在字典中移除该键值对,并返回该键值对

3.有序字典

  1. from collections import OrderedDict

发表评论

表情:
评论列表 (有 0 条评论,513人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pythondict字典

    字典是一系列由键(key)和值(value)配对组成的元素的集合,在 Python3.7+,字典被确定为有序(注意:在 3.6 中,字典有序是一个implementation