python编程:从入门到实践 (第一版) 第六章学习笔记

第6章:字典

字典示例(查)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")
字典的增、改、删
# 创建一个空字典
alien_0 = {}
# 增加键值对
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
# 修改颜色
alien_0['color'] = 'yellow'
print(alien_0)
# 删除键值对
del alien_0['color']
print(alien_0)

输出:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}
{'points': 5}
遍历键值对
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
for key, value in user_0.items():
    print("\nKey:" + key)
    print("Value:" + value)
favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    }
for name, language in favorite_langueages.items():
    print(name.title() + "'s favorite language is " + language + ".")

注意: 即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。

遍历字典中的所有键

不需要使用字典中的值时,方法keys() 很有用

favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    }
for name in favorite_languages.keys():
    print(name.title())

另一种遍历键值对的方式

favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    }
for name in favorite_languages:
    print(name.title() + "'s favorite language is " + favorite_langueages[name] + ".")

注意: 遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages: ,输出将不变。

利用函数sorted() 按顺序遍历所有的键

favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    }
for name in sorted(favorite_languages.keys()):
	print(name.title() + ", thank you for taking the poll."
遍历字典中的所有值

如果你感兴趣的主要是字典包含的值,可使用方法values() ,它返回一个值列表,而不包含任何键。

favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    'tim': 'Python'
    }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language)

输出:

The following languages have been mentioned:
C
Python
Javascript
Rust
Python

这种做法提取字典中所有的值,而没有考虑是否重复。涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的

favorite_languages = {
    'sarah': 'C',
    'jack': 'Python',
    'sam': 'Javascript',
    'bruce': 'Rust',
    'tim': 'Python'
    }
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language)

输出:

The following languages have been mentioned:
Python
Rust
C
Javascript

查资料后,对集合的补充:python3-集合|菜鸟教程

嵌套
列表中存储字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)
字典中存储列表
favorite_languages = {
    'bruce': ['java'],
    'tom': ['python', 'c'],
    'david': ['php', 'rust', 'go'],
    'jack': ['java'],
    }
for name, languages in favorite_languages.items():
    print("\n" + name + "'s favorite languages are:" )
    for language in languages:
        print(language)
字典中存储字典
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())

习题

6-1
user = {
    'firstname': 'burce',
    'lastname': 'zhang',
    'city': 'beijing',
    'age': 18,
    }
print("firstname: " + user['firstname'].title())
print("lastname: " + user['lastname'].title())
print("city: " + user['city'].title())
print("age: " + str(user['age']))
6-2
favorite_numbers = {
    'bruce': 5,
    'tom': 8,
    'jerry': 6,
    }
for name, number in favorite_numbers.items():
    print(name + "'s favorite number is " + str(number) + ".")
6-3
program_vocabulary = {
    'print': '输出到屏幕上',
    'variable': '变量',
    'set': '集合',
    'list': '列表',
    'dict': '字典',
    }
for vocabulary, meaning in program_vocabulary.items():
    print("\n" + vocabulary + ":\n\t" + meaning)
6-5
rivers = {
    'nile': 'egypt',
    'amazon river': 'brazil',
    'yangzi river': 'china',
    }
for name, country in rivers.items():
    print("The " + name.title() + " runs through " + country.title() + ".")
6-6
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
persons = ['jim', 'sam', 'ben', 'phil', 'sarah']
for person in persons:
    if person in favorite_languages.keys():
        print(person.title() + ",thank you for taking the poll!")
    else:
        print(person.title() + ",please take the poll,thank you.")
6-7
user_0 = {
    'firstname': 'burce',
    'lastname': 'zhang',
    'city': 'beijing',
    'age': 18,
    }
user_1 = {
    'firstname': 'jack',
    'lastname': 'ma',
    'city': 'hangzhou',
    'age': 58,
    }
user_2 = {
    'firstname': 'robin',
    'lastname': 'li',
    'city': 'beijing',
    'age': 40,
    }
users = [user_0, user_1, user_2]
for user in users:
    print(user)
6-8
cat = {
    'owner' : 'bruce',
    'type': 'persian',
    }
dog = {
    'owner': 'sam',
    'type': 'korgi',
	}

pets = [cat, dog]
for pet in pets:
    print("This is a " + pet['type'].title() +", its owner is " + pet['owner'] .title()+ ".")
6-9
favorite_places = {
    'tom': ['beijing', 'chengdu', 'shanghai'],
    'jim': ['wuhan', 'chongqing', 'beijing'],
    'bruce': ['wuhan']
    }
for name, places in favorite_places.items():
    if len(places) == 1:
        print("\n" + name + "'s favorite place is " + places[0] + ".")
    else:
        print("\n" + name + "'s favorite places are:")
        for place in places:
            print(place)
6-10
# 与6-9类似
6-11
cities = {
    'wuhan': {
        'country': 'China',
        'population': 11212000,
        'fact': 'Wuhan,different everyday!'
        },
    'beijing': {
        'country': 'China',
        'population': 21536000,
        'fact': 'Some people leave,and some people come in the meantime.'
        }
    }
for city, city_info in cities.items():
    print("\ncity:" + city)
    print("country:" + city_info['country'])
    print("population:" + str(city_info['population']))
    print("fact" + city_info['fact'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值