python从入门到实践 第六章习题 (高级编程技术 week3-2)

python从入门到实践 第六章习题 (高级编程技术 week3-2)

这一节课主要讲的是在python中字典数据结构的使用。

字典的基本使用

6-1 人

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'])

6.3 遍历字典

可以通过以下几个函数来生成字典的相关列表,并使用for来迭代遍历整个字典:
1. dict.items():返回包含键-值对的列表。
1. dict.keys():返回只包含键的列表。
1. dict.values():返回只包含值的列表。

6-5 河流

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())

6-6 调查

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?')

6.4 嵌套

字典,列表之间的相互嵌套。

  1. 在列表中存储字典
  2. 在字典中存储列表
  3. 在字典中存储字典

6-7 人

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'], '.')

6-9 喜欢的地方


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)

6-11

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, ' .')

6.5 小结

这一章学习了一些字典的简单使用方法。

你可能感兴趣的:(高级编程技术)