1. 程式人生 > >python學習之——字典的遍歷

python學習之——字典的遍歷

python學習之——字典的遍歷

1.例如:建立如下儲存五個人,各自喜歡的程式語言的一個字典,我們要遍歷這個字典中的每個鍵值對:

favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
#使用items()返回字典中每個鍵-值對
  for name,language in favorite_languages.items():
    print(name.title()+"'s favorite language is"
+ language.title()+".") #使用keys()返回favorite_language中的所有鍵。 for name in favorite languages.keys(): print(name.title)

遍歷字典時,會預設遍歷所有的鍵,因此,如果將上述程式碼中的
for name in favorite_lanuages.keys() :改為 or name in favorite_lanuages :輸出將不變。

2.按順序遍歷字典中的所有鍵

favorite_languages={
    'jen':'python'
, 'sarah':'c', 'edward':'ruby', 'phil':'python', } #使用sorted()來獲得按特定順序排列表的副本 for name in sorted(favorite_language.keys()): print(name.title()+",thank you for taking the poll.")

3.遍歷字典中的所有值

favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil'
:'python', } for language in favorite_languages.values(): print(language.title()) #為避免有重複的值,採用集合(set) for language in set(favorite_language.values()): print(language.title())

4.字典和列表的巢狀

1.在列表中儲存字典
alien_0包含一個外星人資訊,怎樣將三個外星人資訊存在一起呢,一種辦法是:建立一張外形人列表,其中每個外形人都是一個字典,包含有關該外星人的各種資訊。

alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
alien_2={'color':'red','point':15}

aliens=[alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)
#使用range()生成30個外星人
aliens=[]
for alien_number in range(30):
    new_alien{'color':'green','point':5,'speed':'slow'}
    aliens.append(new_alien)
    #顯示前五個外星人
    for alien aliens[:5]:
        print("...")
    #顯示建立了多少個外星人
    print("Total number of aliens:
        print(alien)

2.在字典中儲存列表

#儲存點pizza的資訊
pizza={
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
      }
#概述所點的披薩
print("you orderede a"+pizza['crust']+"-crust pizza"+"with the following topping:")

for topping in pizza['toppings']:
    print('\t'+topping)

3.在字典中儲存字典

#在字典中儲存字典
users={
    'aeinstein':{
        'frist':'albert',
        'last':'einstein',
        'location':'princetion'

        },
    'mcurie':{
        'frist':'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("\nFull name:"+full_name.title())
        print("\tlocation:"+location.title())