a = {key1 : value1, key2 : value2 ,key3 : value3}
dict={'a':1,'b':2,'b':3}
>>> dict
{'a': 1, 'b': 3}
>>> dict1={'a':123,98.6:88,'c':'efg',('name'):'aa'}
>>> type(dict1)
1、修改/添加字典元素
>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> dict['Age'] = 8 #修改
>>> dict
{'Name': 'Zara', 'Age': 8, 'Class': 'First'}
>>> dict['School'] = "JIAODA" #添加
>>> dict
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'JIAODA'}
>>> dict={"s1":99,"s2":88,"s3":77}
>>> dict1={"s1":34,"s4":56,"s5":90}
>>> dict.update(dict1) #将字典 dict1 的键/值对更新到 dict 中
>>> dict
{'s1': 34, 's2': 88, 's3': 77, 's4': 56, 's5': 90}
2、删除字典元素
>>> dict={'a':1,'b':2,'c':3,'d':4}
>>> del dict['a'] # 删除键是'a'的键值对
>>> dict
{'b': 2, 'c': 3, 'd': 4}
>>> dict.pop('b') # 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。
2
>>> dict
{'c': 3, 'd': 4}
>>> dict.clear() # clear() 删除字典内所有元素 ,清空后字典仍存在
>>> dict
{}
>>> del dict #删除字典,del后字典不再存在,会引发异常
>>> dict
Traceback (most recent call last):
File "", line 1, in
NameError: name 'dict' is not defined
3、查询字典里的值
>>> dict1={'s1':99,'s2':88,'s3':77}
>>> dict1['s1'] #查询字典 dict1 中键 s1 所对应的值
99
>>> dict={"s1":99,"s2":88,"s3":77}
>>> dict.keys()
dict_keys(['s1', 's2', 's3'])
>>> dict.values()
dict_values([99, 88, 77])
>>> dict.items()
dict_items([('s1', 99), ('s2', 88), ('s3', 77)])
>>> a={"s1":34,"s4":56,"s5":90}
>>> len(a)
3