dic1 = {
"name":"Bosh","password":"1234","hobby":{
"girl_name":"花花","weight":120}}
###增
dic1["age"] = 20
print(dic1) #结果 {'name': 'Bosh', 'password': '1234', 'hobby': {'girl_name': '花花', 'weight': 120}, 'age': 20}
result = dic1.setdefault("isMale","True") #键存在,不改动,返回字典中相应的键对应的值;键不存在,在字典中增加新的键值对,并返回相应的值
print(result) #结果 True
print(dic1) #结果 {'name': 'Bosh', 'password': '1234', 'hobby': {'girl_name': '花花', 'weight': 120}, 'age': 20, 'isMale': 'True'}
###查
print(dic1['name']) #print(dic1.get("name")) #结果 Bosh
print(dic1["hobby"]["girl_name"])#print(dic1["hobby"].get("girl_name")) #结果 花花
print(dic1.keys()) #结果 dict_keys(['name', 'password', 'hobby', 'age', 'isMale']),返回一个dict_items
print(list(dic1.keys())) #结果 ['name', 'password', 'hobby', 'age', 'isMale'],返回一个列表
print(dic1.values()) #结果 dict_values(['Bosh', '1234', {'girl_name': '花花', 'weight': 120}, 20, 'True'])
print(dic1.items()) #结果 dict_items([('name', 'Bosh'), ('password', '1234'), ('hobby', {'girl_name': '花花', 'weight': 120}), ('age', 20), ('isMale', 'True')])
###改
dic3 = {
"name":"Bosh","age":20}
dic3["name"] = "Hello"
dic4 = {
"age":50,"hobby":"football"}
dic3.update(dic4)
print(dic3) #结果 {'name': 'Hello', 'age': 50, 'hobby': 'football'}
###删
dic5 = {
'name': 'Hello', 'age': 50, 'hobby': 'football'}
result = dic5.pop("age")
print("result",result,",dic5=",dic5) #结果 result 50 ,dic5= {'name': 'Hello', 'hobby': 'football'}
result2 = dic5.popitem() #随机删除一组键值对
del dic5["name"]
print(dic5) #结果 {'age': 50, 'hobby': 'football'}
dic5.clear()
print(dic5) #结果 {}
###其他
dic2 = dict((("name","Bosh22"),))
print(dic2) #结果 {'name': 'Bosh22'}
dic6 = dict.fromkeys(["name1","name2","name3"],"value")
print(dic6) #结果 {'name1': 'value', 'name2': 'value', 'name3': 'value'}
dic6 = dict.fromkeys(["name1","name2","name3"],["value1","value2"])
print(dic6) #结果 {'name1': ['value1', 'value2'], 'name2': ['value1', 'value2'], 'name3': ['value1', 'value2']}
###嵌套
dic7 ={
"中国":{
"内蒙古":["呼和浩特","鄂尔多斯","呼伦贝尔"],
"黑龙江":{
"哈尔滨":"双城",
"齐齐哈尔":{
"龙沙","建华","铁锋"},
"牡丹江":{
"东安","阳明","绥芬河"},
"佳木斯":["前进","向阳","东风"]
}
},
"America":{
"Alaska","California","Florida","Ohio","Pennsylvania"
},
"Россия":{
" Čelabinsk","Omsk","Krasnojarsk","Čelabinsk"
}
}
print(dic7["中国"]["黑龙江"]["齐齐哈尔"]) #结果 {'龙沙', '建华', '铁锋'}
###遍历
dic8 = {
'name': 'Hello', 'age': 50}
for i in dic8 :
print(i,dic8[i])
for i,v in dic8.items():
print(i,v)