这一节课主要讲的是在python中字典数据结构的使用。
dict={
"first_name" : "Walker",
"last_name" : "Mike",
"age" : "18",
"city" : "New York",
}
print('the first name is ', dict['first_name'])
print('the last name is ', dict['last_name'])
print('the age is ', dict['age'])
print('the city is ', dict['city'])
可以通过以下几个函数来生成字典的相关列表,并使用for来迭代遍历整个字典:
1. dict.items():返回包含键-值对的列表。
1. dict.keys():返回只包含键的列表。
1. dict.values():返回只包含值的列表。
rivers = {
'nile':'egypt',
'Yellow River':'china',
'Yangtze River':'china',
}
for river,country in rivers.items():
print('The ', river.title(), ' runs through Egypt.')
for river in rivers.keys():
print('The name of river is ',river.title())
for country in rivers.items():
print('The country is ', country.title())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
users = ['jen','john','ergou','mike','sarah','edward','phil']
print("The following languages have been mentioned:")
for name in users:
if name in favorite_languages.keys():
print('Thank you, ' + name.title())
else:
print('Would you participate in the survey?')
字典,列表之间的相互嵌套。
walker={
"first_name" : "Walker",
"last_name" : "Mike",
"age" : "18",
"city" : "New York",
}
john={
"first_name" : "John",
"last_name" : "Mike",
"age" : "19",
"city" : "New York",
}
lily={
"first_name" : "lily",
"last_name" : "Mike",
"age" : "17",
"city" : "New York",
}
people = [walker, john, lily]
for person in people:
print(person['first_name'].title(), persion['last_name'].title(), ' is ', persion['age'], ' now living in ', person['city'], '.')
favorite_places = {
'john':['beijing', 'hang zhou'],
'mike':['guang zhou'],
'lily':['si chuang'],
}
for person, places in favorite_places.item():
print(person.title(), ' likes these places:')
for place in places:
print('|',place)
cities = {}
cities['Guang Zhou'] = {
'country':'china',
'population':82342523,
'fact':'This city is beautiful!',
}
cities['Hang Zhou'] = {
'country':'china',
'population':12982415,
'fact':'This city is beautiful, too!',
}
cities['Beijing'] = {
'country':'china',
'population':129832415,
'fact':'This city is big and beautiful!',
}
for city_name in cities.keys():
for arg, content in cities[city_name].items():
print('The ', arg, ,' of ', city_name, ' is ', content, ' .')
这一章学习了一些字典的简单使用方法。