五.字典(续)
⑧可以不用遍历字典中的全部元素,只遍历字典中的键或值都是可行的。
book={
'front_cover'='black'
'back_cover'='white'
}
for cover in book.keys():
print(cover.title() + "has its color.")
输出:
Front_cover has its color.
Back_cover has its color.
book={
'front_cover'='black'
'back_cover'='white'
}
for color in book.values():
print("The book has "+color+" color.")
输出:
The book has black color.
The book has white color.
遍历字典时,会默认遍历所有的键。方法keys()返回一个列表,其中包含字典中所有的键。
⑨字典总是明确地记录键和值之间的关联关系,但获取字典元素时,获取顺序是不可测的。要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。如使用函数sorted()。
books={
'Alala':'fairy_tale'
'Zozo':'text'
'DAdada':'fiction'
'Sisi':'novel'
}
for book in sorted(books.keys()):
print(book.title() + "is a good book.")
输出:
Alala is a good book.
DAdada is a good book.
Sisi is a good book.
Zozo is a good book.
⑩当使用values()来遍历值时,最终的列表可能包含大量重复项。因为这种做法提取字典中所有的值,但不考虑值是否重复。为剔除重复项,可使用集合。集合类似于列表,但每个元素都必须是独一无二的。
books={
'Alala':'fairy_tale'
'Zozo':'text'
'DAdada':'fiction'
'Sisi':'novel'
'Cucu':'novel'
}
for book in set(books.values()):
print(book.title())
输出:
Fairy_tale
Text
Fiction
Novel
通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
⑪将一系列字典存储在列表中,将列表作为值存储在字典中都叫嵌套。可以在列表中嵌套字典,在字典中嵌套列表,在字典中嵌套字典。
book_0={'color':black,'name':'Wwww'}
book_1={'color':white,'name':'Zzzz'}
book_2={'color':grey,'name':'Kkkk'}
books=[book_0,book_1,book_2]
for book in books:
print(book)
输出:
{'color':black,'name':'Wwww'}
{'color':white,'name':'Zzzz'}
{'color':grey,'name':'Kkkk'}
books={
'name':['Aaa','Bibi','mius'],
color:'white'
}
print("Books have white cover are :")
for book_name in books['name']:
print(book_name)
输出:
Aaa
Bibi
mius
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。
字典中也可以存储字典:
books={
'Alala':{'color':'black'
'stories':6
}
'Cucu':{'color':'white'
'stories':8
}
'Zll':{'color':'grey'
'stories':11
}
}