字典的创建方式:
#__author:"hanhankeji" #date: 2019/12/5 #Dictionary(字典) #方法1 dic1 = {"name":"hanhankeji","age":35 ,"hobby":{"girl_name":"大锤","age":30},"is_handsome":True} print(dic1) #方法2 # a = list((1,2,3,3,55,66)) # print(a) dic2 = dict((("name","hanhankeji"),("age",35))) print(dic2) #方法3 dic3 = dict((["name","hanhankeji"],["age",35],("hobby","大锤"))) print(dic3)
输出:
{'name': 'hanhankeji', 'age': 35, 'hobby': {'girl_name': '大锤', 'age': 30}, 'is_handsome': True} {'name': 'hanhankeji', 'age': 35} {'name': 'hanhankeji', 'age': 35, 'hobby': '大锤'}
增加字典:
#字典的增加: dic2 = dict((("name","hanhankeji"),("age",35))) dic2["hobby"] = "大锤" print(dic2) #{'name': 'hanhankeji', 'age': 35, 'hobby': '大锤'}
运行:
{'name': 'hanhankeji', 'age': 35, 'hobby': '大锤'}
对字典的操作:
#字典的增加: dic2 = dict((("name","hanhankeji"),("age",35))) dic2["hobby"] = "大锤" print(dic2) #{'name': 'hanhankeji', 'age': 35, 'hobby': '大锤'} dic2.setdefault("is_handsome",True) print(dic2) #查/只能通过键名去查找: print(dic2["is_handsome"]) #True print(dic2.keys()) print(list(dic2.keys())) print(list(dic2.values())) #转换成列表 没有取件 ['hanhankeji', 35, '大锤', True] print(list(dic2.items())) #键值对直接取出来[('name', 'hanhankeji'), ('age', 35), ('hobby', '大锤'), ('is_handsome', True)] #改: dic3 ={"name":"hanhankeji","age":35,"hobby":"大锤"} dic4 = {"1":"111","2":"2222"} dic3.update(dic4)#把dic4的值放3里面去,做修改 print(dic3)# {'name': 'hanhankeji', 'age': 35, 'hobby': '大锤', '1': '111', '2': '2222'} dic5 = {"name":"xinxinmingzhi",}#测试键一样的会不会覆盖之前的键值对! dic3.update(dic5) print(dic3)#{'name': 'xinxinmingzhi', 'age': 35, 'hobby': '大锤', '1': '111', '2': '2222'}
{'name': 'hanhankeji', 'age': 35, 'hobby': '大锤'} {'name': 'hanhankeji', 'age': 35, 'hobby': '大锤', 'is_handsome': True} True dict_keys(['name', 'age', 'hobby', 'is_handsome']) ['name', 'age', 'hobby', 'is_handsome'] ['hanhankeji', 35, '大锤', True] [('name', 'hanhankeji'), ('age', 35), ('hobby', '大锤'), ('is_handsome', True)] {'name': 'hanhankeji', 'age': 35, 'hobby': '大锤', '1': '111', '2': '2222'} {'name': 'xinxinmingzhi', 'age': 35, 'hobby': '大锤', '1': '111', '2': '2222'}