Dictionary use {}
Express
There are two things in the dictionary. The first is key
You can understand this thing as an index , When we have this key
When , You don't need an index
# Define a dictionary
a = {"name" : "wangyangzheng","age" : 18,"school" : "asthu"}
# key :name, age,school
# value :wangyangzheng,age,asthu
# visit
print(a ["name"])
# Remember to add ""
# If it is not added, it will happen name Undefined errors
Dictionaries are out of order , If we judge whether two dictionaries are equal , The order of dictionary elements is different , But the elements are the same , It's the same
a = {'1' : 1, '2' : 2}
b = {'2' : 2, '1' : 1}
print(a == b)
# Output True
spam = {'size' : 'fat','color' : 'gray','disposition' : 'loud'}
# Return a list like this
print(spam.keys())
# Output one by one spam Key
for i in spam.keys():
print(i)
spam = {'size' : 'fat','color' : 'gray' ,'disposition' : 'loud'}
print(spam.values())
# Output the values of the dictionary one by one
for i in spam.values():
print(i)
spam = {'size' : 'fat','color' : 'gray' ,'disposition' : 'loud'}
print(spam.items())
# Output key value pairs one by one
for i in spam.items():
print(i)
If this value exists, it is in, If not, it's not int
spam = {'size' : 'fat','color' : 'gray','disposition' : 'loud'}
print('name' in spam.keys()) # return False Express 'name' No spam Key
print('gray' in spam.values())# return True Express 'gray' yes spam Value
print('gray' not in spam.keys())# return False Express 'gray' No spam Key
spam = {'apple' : 5,'cups' : 2}
print("I'm bring" + str(spam.get('cups',0)) + 'cups' ) # 2
print("I'm bring" + str(spam.get('pen',0)) + 'pens') # Output standby value 0
If this key doesn't exist , Then put both keys and values into the dictionary
spam = {'1':1}
print(spam.setdefault('1',0))
print(spam.setdefault('2',2))
We find that the output value of the third line is 2
This is because ’2’ This key doesn't exist ,setdefault Method adds both the key and the value
We can verify it
print(spam)
It was found that it was