字典創(chuàng)建
字典使用花括號(hào) {}表示梁厉, 字典的元素采用鍵值對(duì)(key-value)的形式存儲(chǔ),字典的每個(gè)鍵值對(duì)用冒號(hào) : 分割意乓,每個(gè)鍵值對(duì)之間用逗號(hào)分割移盆。
di ={'name':"bx",'age':26}
# {'name': 'bx', 'age': 26}
dict函數(shù)
student = [('name', 'xiaoming'), ('age', 18)]
d = dict(student)
print(d)
detail = dict(name='xiaohong',age=20)
print(detail)
keys
所有key的列表
aDict = {"a":1, "b":2, "c":3}
print(aDict.keys())
['a', 'b', 'c']
values
aDict = {"a":1, "b":2, "c":3}
print(aDict.values())
[1, 2, 3]
items
返回含所有(鍵,值)元祖的列表
student = {'name': 'xiaoming', 'age': 18}
print(student.items())
##dict_items([('name', 'xiaoming'), ('age', 18)])
len
鍵值對(duì)的個(gè)數(shù)
aDict = {"a":1, "b":2, "c":3}
print(len(aDict))
3
修改數(shù)據(jù)
student = {'name': 'xiaoming', 'age': 18}
print(student)
student['name'] = 'xiaowang'
student['age'] = 19
print(student)
刪除元素
一種是del另外一種是調(diào)用pop(key)
student = {'name': 'xiaoming', 'age': 18}
del student['name']
print(student)
student.pop('age')
print(student)
判斷元素是否存在
if "e" in dict:
print("存在key等于e")
else:
print("不存在key等于e")
if dict.get("b") != None:
print("存在key等于b")
else:
print("不存在key等于b")
字典推導(dǎo)式
{key:value for循環(huán) if判斷}
d = {'name': 'bx', 'age': 18}
di = {value: key for key, value in d.items()}
print(di)
##{'bx': 'name', 18: 'age'}
clear
刪除字典內(nèi)所有的元素
student = {'name': 'xiaoming', 'age': 18}
student.clear()
print(student)
get
dict.get(key.default=None)key代表要查找的鍵,如果沒(méi)有找到就是用的設(shè)置default默認(rèn)值
student = {'name': 'xiaoming', 'age': 18}
print(student.get('age'))
print(student.get('gender','none'))