【Python基础】之字典dict

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

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

dic = {}

dic = dict()

dic = {1:'one', 2:'two',3:'three',4:'four'}
for i in dic:
    print(i) #输出键1 2 3 4
for i in dic.keys():
    print(i)#输出键1 2 3 4
for i in dic.values():
    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():
    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,在字典中移除该键值对,并返回该键值对

猜你喜欢

转载自blog.csdn.net/lincoco49/article/details/89318886