列举使用python3dict字典方法功能

clear(清空字典内容)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
print(stu.clear())
#输出:none

copy(拷贝字典)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
stu2 = stu.copy()
print(stu2)

fromkeys(指定一个列表,把列表中的值作为字典的key,生成一个字典)

name = [‘tom’,’lucy’,’sam’]
print(dict.fromkeys(name))
print(dict.fromkeys(name,25)) #指定默认值
#输出:{‘tom’: none, ‘lucy’: none, ‘sam’: none}
# {‘tom’: 25, ‘lucy’: 25, ‘sam’: 25}

get(指定key,获取对应的值)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
print(stu.get(‘num2’))
#输出:lucy

items(返回由“键值对组成元素“的列表)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
print(stu.items())
#输出:dict_items([(‘num2’, ‘lucy’), (‘num3’, ‘sam’), (‘num1’, ‘tom’)])

keys(获取字典所有的key)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
print(stu.keys())
#输出:dict_keys([‘num3’, ‘num1’, ‘num2’])

pop(获取指定key的value,并在字典中删除)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
name = stu.pop(‘num2’)
print(name,stu)
#输出:lucy {‘num1’: ‘tom’, ‘num3’: ‘sam’}

popitem(随机获取某个键值对,并在字典中删除)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
name = stu.popitem()
print(name,stu)
#输出:(‘num2’, ‘lucy’) {‘num3’: ‘sam’, ‘num1’: ‘tom’}

setdefault(获取指定key的value,如果key不存在,则创建)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
name = stu.setdefault(‘num5’)
print(name,stu)
#输出:none {‘num1’: ‘tom’, ‘num2’: ‘lucy’, ‘num5’: none, ‘num3’: ‘sam’}

update(添加键 – 值对到字典)

stu = {
‘num1′:’tom’,
‘num2′:’lucy’,
‘num3′:’sam’,
}
stu.update({‘num4′:’ben’})
print(stu)
#输出:{‘num2’: ‘lucy’, ‘num3’: ‘sam’, ‘num1’: ‘tom’, ‘num4’: ‘ben’}

以上就是列举使用python3 dict字典方法功能的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论