The dictionary uses key value pairs (key-value) How to store , Elements can be key visit . Dictionaries are written by Curly braces { }
Enclosed contains ,key : value Two parts .
# Create a dictionary
dict1={
'name':'zhang','age':30,'city':'Beijing'}
print(dict1)
{‘name’: ‘zhang’, ‘age’: 30, ‘city’: ‘Beijing’}
# Get elements : adopt Key obtain value value
dict1.get('age')
30
dict1.get('city')
‘Beijing’
# Add elements to the dictionary
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’}
# Delete an element
del dict1['gender']
print(dict1)
{‘name’: ‘zhang’, ‘age’: 35, ‘city’: ‘Beijing’}
#items()
dict1.items()
dict_items([(‘name’, ‘zhang’), (‘age’, 35), (‘city’, ‘Beijing’)])
# Ergodic dictionary
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