程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

0 basic learning python (16)

編輯:Python

Dictionaries

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!

Add key value pair

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.

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved