大学Python学习课件字典练习
- 格式:docx
- 大小:17.19 KB
- 文档页数:1
《Python编程从入门到实践》第六章——字典习题6-5 创建一个字典,在其中存储三条大河流及其流经的国家,使用循环为每条河流打印一条消息。
rivers = {'尼罗河' : '埃及''长江': '中国''亚马逊' : '巴西'}for river country in rivers.items():print ("The " +str(river) +" runs through " +str(country) +".")for river in sorted(rivers.keys()): #使用keys() 遍历字典中的所有键print (river)for country in rivers.values(): #使用value() 遍历字典中的所有值print (country)6-1、6-7 使用字典来存储熟人的信息,包括名、姓、年龄和居住的城市。
该字典应包含键first_name、last_name、age和city。
然后将这字典都存储在一个名为people的列表中,遍历这个列表。
user_0 = {'first_name': '森''last_name': '郭''age': '18''city': 'Newyork'}user_1 = {'first_name': '橙''last_name': '江''age': '16''city': 'Peking'}user_2 = {'first_name': '熊''last_name': '巴索罗米''age': '16''city': 'Paris'}people = [user_0 user_1 user_2] (#在列表中嵌套字典)for user in people:print(user)6-2 、6-8 使用一个字典来存储一些人喜欢的数字。
python字典实训题目这里有一个关于Python字典(dictionary)的实训题目:实训题目:作为一个图书管理员,需要创建一个图书馆的书籍目录。
使用Python字典来管理这个图书目录,能够进行以下操作:1.添加书籍:将书名作为键,书籍信息(如作者、出版日期等)作为值添加到图书目录中。
2.检查书籍是否存在:输入书名,检查该书是否在图书目录中。
3.获取书籍信息:输入书名,获取对应书籍的信息(如作者、出版日期等)。
4.删除书籍:输入书名,从图书目录中删除对应的书籍信息。
示例:●创建一个空的图书目录library_catalog={}●添加书籍信息def add_book(title,author,published_date):library_catalog[title]={"Author":author,"Published Date":published_date}print(f"Added'{title}'to the library catalog.")●检查书籍是否存在def check_book(title):if title in library_catalog:print(f"'{title}'exists in the library catalog.")else:print(f"'{title}'does not exist in the library catalog.")●获取书籍信息def get_book_info(title):if title in library_catalog:info=library_catalog[title]print(f"Information for'{title}':")for key,value in info.items():print(f"{key}:{value}")else:print(f"'{title}'does not exist in the library catalog.")●删除书籍信息def remove_book(title):if title in library_catalog:del library_catalog[title]print(f"Removed'{title}'from the library catalog.")else:print(f"'{title}'does not exist in the library catalog.")●示例操作add_book("Python Crash Course","Eric Matthes","November 2019")check_book("Python Crash Course")get_book_info("Python Crash Course")remove_book("Python Crash Course")这个实训题目可以帮助练习使用字典来创建一个简单的图书目录,并进行书籍的添加、检查、获取信息和删除操作。
python基础练习(六)字典_练习 1# 字典2"""3字典简介:4我们上学的时候都⽤过字典,如果遇到不明⽩的字,只要知道其拼⾳⾸字母就能找到其准确位置,故⽽知道其含义~5如:“我”,先找到 w 再找到 o 就能找到 “我” 字6字典 = {'w':'o'} 这就是字典的格式,当然,组合很多不⽌这⼀种7"""8"""9格式:10在我们程序中,字典:11earth = {'sea':'big_west_ocean','area':50,'position':'earth'}12dict = {key:value}13字典和列表⼀样,也能够存储多个数据14字典找某个元素时,是根据key来获取元素15字典的每个元素由2部分组成,键:值,【例如:'area':50】16"""17# 1.根据键访问值——[]18 erth = {'sea':'big_west_ocean','area':50,'position':'earth'}19print(erth['sea']) # big_west_ocean2021# print(erth['abc']) # 返回报错如下(如果键不存在就会报错)22"""23Traceback (most recent call last):24 File "F:/test/7字典.py", line 21, in <module>25 print(erth['abc'])26KeyError: 'abc'27"""2829# 2.根据键访问值——.get()30 erth = {'sea':'big_west_ocean','area':50,'position':'earth'}31print(erth.get("abc")) # None32print(erth.get("abc","参数不存在")) # 参数不存在33print(erth.get("sea")) # big_west_ocean3435# 3.字典的常见操作36# 3.1 修改元素【字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改】37 erth['area'] = 10038print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}3940# 3.2 添加元素41"""42在上⾯说了,当访问不存在的元素时会报错43那么在我们使⽤:变量名['键'] = 数据时,这个“键”不存在字典中,那么会新增这个元素44"""45 erth["aaaa"] = "bbbb"46print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth', 'aaaa': 'bbbb'}4748# 3.3 删除元素49"""50对元素的删除操作,有两种⽅式51del: 删除指定元素,删除整个字典52clear():清空整个字典53"""54# del 删除指定元素55 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth', 'aaaa': 'bbbb'}56del erth['aaaa']57print(erth) # {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}5859# del 删除字典60 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}61del erth62# print(erth) # 此步骤不⽤运⾏就会报错,变量不存在6364# clear 清空整个字典65 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}66 erth.clear()67print(erth) # 返回 {}6869# 4 查看字典中,键值对的个数:len【列表中也是⼀样的】70 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}71print(len(erth)) # 37273# 5.1 查看字典中所有的key: key() (取出字典中所有的key值,返回的是列表)74 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}75print(erth.keys()) # dict_keys(['sea', 'area', 'position'])7677# 5.2 查看字典中所有的 value: value() (取出字典中所有的value值,返回的是列表)78 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}79print(erth.values()) # dict_values(['big_west_ocean', 100, 'earth'])8081# 6 查看字典中的元素:items() (返回的是包含所有(键、值)元素的列表)(也可以说是字典转列表的⽅法) 82 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}83print(erth.items()) # dict_items([('sea', 'big_west_ocean'), ('area', 100), ('position', 'earth')])8485# 7 判断某个键是否存在字典中返回 True 或者 False86 erth = {'sea': 'big_west_ocean', 'area': 100, 'position': 'earth'}87print(erth.__contains__("sea")) # True88print(erth.__contains__("sea123")) # False。
python字典练习题Python中的字典(Dictionary)是一种可变容器,可以存储、索引和排序键值对。
字典通过使用键来访问值,而不是使用位置索引。
本篇文章将为您提供一些Python字典的练习题,帮助您提高对字典的理解和运用。
1. 创建字典首先,我们需要学会如何创建一个字典。
请按照以下要求创建一个字典,并将其存储在变量`my_dict`中:- 键-值对包括键`name`和相应的值`"Tom"`;- 键`age`和相应的值`25`;- 键`city`和相应的值`"New York"`。
2. 访问字典中的值现在,我们要学习如何访问字典中的值。
请完成以下任务:- 打印输出字典中`name`对应的值;- 打印输出字典中`age`对应的值;- 打印输出字典中`city`对应的值。
3. 修改字典中的值字典是可变的,允许我们随时修改键对应的值。
请完成以下任务:- 将字典中`name`对应的值修改为`"Jerry"`;- 将字典中`age`对应的值增加`5`;- 打印输出被修改后的字典。
4. 添加键值对如果需要,在字典中添加键值对也是非常简单的。
请按照以下要求向字典中添加一个键值对:- 键为`"gender"`,值为`"male"`。
5. 删除键值对有时,我们需要删除字典中的某个键值对。
请完成以下任务:- 删除字典中键为`"city"`的键值对;- 打印输出被删除键值对后的字典。
6. 遍历字典遍历字典是十分常见的操作,它让我们能够同步访问字典中的键和值。
请完成以下任务:- 使用循环遍历并打印输出字典中的所有键;- 使用循环遍历并打印输出字典中的所有值;- 使用循环遍历并打印输出字典中的所有键值对。
7. 获取字典长度有时,我们需要知道字典中包含多少个键值对。
请找到并使用一个函数,打印输出字典中键值对的个数。
python字典部分练习题字典作为Python中一种重要的数据结构,能够高效地存储和检索键值对。
在本文中,我们将介绍一些Python字典的基本用法,并提供一些练习题供读者实践。
一、字典的基本操作字典的创建和初始化:d = {} # 创建一个空字典d = {'apple': 1, 'banana': 2, 'orange': 3} # 创建一个带初始键值对的字典字典中添加或修改键值对:d['apple'] = 5 # 添加键值对'apple': 5,或修改已有键'apple'的值为5字典中删除键值对:del d['banana'] # 删除键为'banana'的键值对字典中检索键值对:value = d['apple'] # 根据键'apple'检索对应的值判断键是否存在:key_exists = 'banana' in d # 判断键'banana'是否存在于字典d中二、练习题1. 题目描述:给定一个字典my_dict,请尝试输出该字典的所有键。
输入:my_dict = {'apple': 1, 'banana': 2, 'orange': 3}输出:apple, banana, orange解答:```pythonmy_dict = {'apple': 1, 'banana': 2, 'orange': 3}keys = my_dict.keys()keys_str = ', '.join(keys)print(keys_str)```2. 题目描述:给定一个字典my_dict,请尝试输出该字典的所有值。
python学习之字典(Dictionary)练习Python字典是另⼀种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型字典中分为键值对, key 类型需要时被哈希。
value 类型可以是字符串、数字、元组等其他容器模型字典的键不能是list类型1 a=[1,2,4,4]2 dict3={a:'dfdf'} #运⾏报错3.dict5={'No':'1', b:'zhangsan','age':'20'}报错为:正如错误提⽰,list/set/dict 均不可被哈希。
这⼀异常通常出现在,调⽤ set(…) 来构造⼀个 set (集合类型)时,set() 需要传递进来可哈希的元素(hashable items)list、set、dict:是不可哈希的1 list.__hash__;#结果为None2 set.__hash__; #结果为None3 dict.__hash__; #结果为Noneint、float、str、tuple:是可以哈希的print int.__hash__;# <slot wrapper '__hash__' of 'int' objects>print float.__hash__; #<slot wrapper '__hash__' of 'float' objects>print str.__hash__; #<slot wrapper '__hash__' of 'str' objects>print tuple.__hash__;#<slot wrapper '__hash__' of 'tuple' objects>删除字典元素1 删单⼀的元素2 清空字典dict7 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};print dict7; #{'Age': 7, 'Name': 'Zara', 'Class': 'First'}# 清除key为:Name的键值对del dict7['Name'];print dict7; #{'Age': 7, 'Class': 'First'}dict7.clear(); #清除所有的键值对print dict7; # {}del dict7;print dict7; #报错 dict7 未定义字典键字典键不能有重复出现:键赋值时后⾯的赋值会把前⾯的覆盖掉⽐如dict8= {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};print dict8; # 输出结果为{'Age': 7, 'Name': 'Manni'}print dict8['Name'] #Manni六、字典内置函数&⽅法Python字典包含了以下内置函数:1、cmp(dict1, dict2):⽐较两个字典元素。