The dictionary includes keys , Value two , General keys and values use : separate . Each key value is separated by commas , The whole dictionary is included in {} Under curly brackets .
For example, we want to build a game against aliens , These aliens have different colors and scores , So we need a dictionary .
Want to get the value related to the key , You can specify the dictionary name, followed by the key in square brackets .
alien_0={
'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
Finally, we visit two lines of code and the result is as follows .
green
5
When we get his score after shooting an alien, we can use the whole code below to determine how many points we should get .
alien_0={
'color':'green','points':5}
new_ponits=alien_0['points']
print(f"you just earned {
new_points}ponits!")
We get and keys from the dictionary points Associated value , And assign this value to the variable new_points, Next, convert this integer to a string , And print out a message , Point out how many points the player got .
you just earned 5 points!
We can set a coordinate for the alien , And we can add his coordinates to the dictionary .
alien_0={
'color':'green','points':5}
print(alien_0)
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
{
'color':'green','points':5}
{
'color':'green','points':5,'y_position':25,'x_poisition':0}
Of course, we can also create an empty list , Then add key value pairs to the dictionary , We can first define a dictionary using curly braces , Then add key value pairs in separate lines .
alien_0={
}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
{
'color':'green','points':5}
Of course, we sometimes need to modify the things in the dictionary , We can specify the dictionary name in turn 、 A key enclosed in square brackets , And the new value associated with the key .
alien_0={
'color';'green'}
print(f"the alien is {
alien_0['color']}.")
alien_0['color']='yellow'
print(f"the alien is now {
alien_0['color']}3")
We will green The color of is changed to yellow.
After output is
the alien is green.
the alien is now yellow.