字典采用鍵值對(key-value)的方式存儲,元素可以通過 key 訪問。字典是由花括號{ }
括起來的包含,key : value 兩部分。
#創建一個字典
dict1={
'name':'zhang','age':30,'city':'Beijing'}
print(dict1)
{‘name’: ‘zhang’, ‘age’: 30, ‘city’: ‘Beijing’}
#獲取元素:通過Key獲取value值
dict1.get('age')
30
dict1.get('city')
‘Beijing’
#給字典增加元素
dict1['gender']='Male'
print(dict1)
{‘name’: ‘zhang’, ‘age’: 30, ‘city’: ‘Beijing’, ‘gender’: ‘Male’}
dict1['age']=35
print(dict1)
{‘name’: ‘zhang’, ‘age’: 35, ‘city’: ‘Beijing’, ‘gender’: ‘Male’}
#刪除某個元素
del dict1['gender']
print(dict1)
{‘name’: ‘zhang’, ‘age’: 35, ‘city’: ‘Beijing’}
#items()
dict1.items()
dict_items([(‘name’, ‘zhang’), (‘age’, 35), (‘city’, ‘Beijing’)])
#遍歷字典
for key,value in dict1.items():
print(key+":",end="")
print(value)
name:zhang
age:35
city:Beijing
dict1.keys()
dict_keys([‘name’, ‘age’, ‘city’])
for key in dict1.keys():
print(key)
name
age
city