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

21-day Python Advanced Learning Challenge punch card------Day 4 (dictionary)

編輯:Python

活動地址:CSDN21天學習挑戰賽

學習的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾.各位小伙伴,如果您:
想系統/深入學習某技術知識點…
一個人摸索學習很難堅持,想組團高效學習…
想寫博客但無從下手,急需寫作干貨注入能量…
熱愛寫作,願意讓自己成為更好的人…


歡迎參與CSDN學習挑戰賽,成為更好的自己,請參考活動中各位優質專欄博主的免費高質量專欄資源(這部分優質資源是活動限時免費開放喔~),按照自身的學習領域和學習進度學習並記錄自己的學習過程.您可以從以下3個方面任選其一著手(不強制),或者按照自己的理解發布專欄學習作品,參考如下:

‘’’

語法:
字典名 = {
'鍵':'值','鍵':'值',....}
例如:
test = {
'color':'pink','points':7}
print(test['color'])
print(test['points'])

‘’’

#例2:testThe keys and values ​​in are unchanged,We get the relevant keys and values ​​from the dictionary,Store this value in new_points中
#Then proceed as follows,需要將new_pointsThe integer type is converted to a string

new_points = test['points']
print("You just earned " + str(new_points) + "points !")

#例3、Add a new key-value pair to the dictionary,鍵為 x_position,值為0;鍵為 y_position,值為25

test = {
'color':'pink','points': 7 }
print(test)
test['x_position'] = 0 #Add a new key-value pair to the dictionary,鍵為 x_position,值為0
test['y_position'] = 25 #Add a new key-value pair to the dictionary,鍵為 y_position,值為25
print(test)

#例4:Create empty dictionary and add values ​​separately

test1 = {
 }
#Branches add new key-value pairs
test1['color'] = 'blue'
test1['points'] = 5
print(test1)

#例5:Change the content of the key pair value in the dictionary and print it

test2 = {
'color':'red'}
print('The color is ' + test2['color'] + '.')
#將red修改為pink
test2['color'] = 'yellow'
print("The test2 new color is " + test2['color'] + '.')

#例6:用if-elifto judge the value,Then replace the value

test3 = {
'x_position':0,'y_position':25,'speed':'medium'}
print('Original x-position:' + str(test3['x_position']) )
#向右移動test
#據外星人當前速度決定將其移動多遠
if test3['speed'] == 'slow':
x_increment = 1
elif test3['speed'] = 'medium':
x_increment = 2
else:
# test3 速度過快
x_increment = 3
test3['x_position'] = test3['x_position'] + x_increment
print('New x-position:' + str(test3['x_position']))

#例7:刪除鍵值,使用del語句指定字典名和要刪除的鍵

test4{
'color':'white','points':9}
print(test4)
del test4['points'] #delStatements are completely removed
print(test4)

#例8:Use multiple lines to define dictionaries,Press Enter after entering the opening curly brace,縮進,指定鍵值對

test5 = {

'name':'test5',
'number':5,
'power':'88W',
}
print('The user is:' + test5['name'].title() + '.') #此處title()是將test5Exhibit in title form

#例9:用for循環遍歷字典,聲明2variables are used to store keys and values;接下來的for循環中,pythonStore each key value in key,value2個變量中

test6 = {

'username':'test6',
'first':'t',
'last':6,
}
#用for循環遍歷字典,聲明2variables are used to store keys and values,
#接下來的for循環中,pythonStore each key value in key,value2個變量中
for k,v in test6.items():
print("\nKey:" + k)
print("Value:" + v)

#例10:用for循環遍歷字典,聲明2variables are used to store keys and values,Store the key in a variablename中,Values ​​are stored in variableslanguages中

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#用for循環遍歷字典,聲明2variables are used to store keys and values,
#Store the key in a variablename中,Values ​​are stored in variableslanguages中
for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")

#例11:使用方法key()提取字典中所有的鍵,and store the key to a variablename中

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#使用方法key()提取字典中所有的鍵,and store the key to a variablename中
for name in favorite_languages.key():
print(name.title())

#例12:if 測試,Determine key-value pairs,If the name is in the listfriends中,就打印一句問候語

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_language.keys():
print(name.title())
if name in friends:
#if 測試,If the name is in the listfriends中,就打印一句問候語
print('Hi' + name.title() + ', I see your favorite language is' + favorite_languages[name].title() + '!')

#例13:Judge the following dictionarykey中是否包含 erin,Print if not present’Erin,Please take our poll !’

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print('Erin,Please take our poll !')

#例14:使用函數sorted對列表臨時排序.讓python列出所有鍵,Sort before traversing

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#使用函數sorted對列表臨時排序.讓python列出所有鍵,Sort before traversing
for name in sorted(favorite_languages.keys()):
print(name.title() + ', thank you for taking the poll .')

#例15:Note in the code above set 用集合setDuplicates can be eliminatedpython,此處用values()method to extract the value of the dictionary

favorite_languages = {

'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print('The follwing language have been memtioned :')
for language in set favorite_languages.values():
#Note in the code above set 用集合setDuplicates can be eliminatedpython
#此處用values()method to extract the value of the dictionary
print(language.title())

#例16:將3dictionary into the listtests中,然後使用for循環遍歷列表,Print out the corresponding key-value pair

test_1 = {
'color':'white','point':5}
test_2 = {
'color':'pink','point':6}
test_3 = {
'color':'blue','point':8}
#將3dictionary into the listtests中
tests = [test_1,test_2,test_3]
#使用for循環遍歷列表
for test in tests:
print(test)

#例17:
#Create one for storagetest的空列表
#創建30個紅色的test
#使用函數 range()生成30個test
#創建new_test字典,包含3對鍵值
#顯示前5個test
#Shows how many are createdtest

tests = []
#創建30個紅色的test
#使用函數 range()生成30個test
for test_number in range(30):
#創建new_test字典,包含3對鍵值
new_test = {
'color':'red','points':5,'speed':'slow'}
tests.append(new_test)
#顯示前5個test
for test in tests[:5]:
print(test)
print('...')
#Shows how many are createdtest
print('Total number of tests:' + str(len(aliens)))

#例18:
#Create one for storagetest的空列表

tests = []
#創建30個紅色的test
#使用函數range()打印0-29
for test_number in range(0,30):
#創建new_test字典,包含3對鍵值
new_test = {
'color':'red','points':5,'speed':'slow'}
tests.append(new_test)
#for循環,指定索引0-3,也就是元素0 1 2
for test in tests[0:3]:
#使用if進行測試,Check if key equalsred,如果通過,執行ifTest the indented code behind
if test['color'] == 'red':
test['color'] = 'yellow'
test['speed'] = 'medium'
test['points'] = 10
#顯示前5個test
for test in tests[:5]:
print(test)
print('...')

#例19:
#Stores information about all pizza orders

pizza = {

'crust':'thick',
'toppings':['mushrooms','extra cheese'], #Here the list is nested in a dictionary
}
#概述所點的披薩
print('You ordered a ' + pizza['crust'] + '-crust pizza' +
'with the following toppings:')
for topping in pizza['toppings']:
print('\t' + topping)

#例20:聲明一個favorite_language字典,然後使用name,language Get the key-value pairs of the dictionary separately in the loop,And re-acquire a new string through character splicing,打印出來

favorite_language = {

'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,language in favorite_languages.items():
print('\n'+ name.title() + "'s favorite languages are:")
for language in languages:
print('\t' + language.title())

#例21:聲明一個users字典,然後使用username,user_info Get the key-value pairs of the dictionary separately in the loop,And re-acquire a new string through character splicing,打印出來

users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton'},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',},
}
for username,user_info in users.items():
print("\nUsername:" + username)
full_name = user_info['first'] + " " + user_info['last']
location= user_info['location']
print("\tFull name:" + full_name.title())
print("\tLocation:" + location.title())

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