chapter6 字典

2024-03-02 13:30
文章标签 字典 chapter6

本文主要是介绍chapter6 字典,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

  • Python中,字典放在花括号{}中的一系列键-值对表示
  • 获取与键相关的值,依次指定字典名和放在花括号内的键
  • del语句将相应的键-值对彻底删除
  • 遍历所有的键-值对
user_0 ={'username':'efermi','first':'enrico','last':'fermi',
}for key,value in user_0.items()://编写用于遍历字典的for循环,声明两个变量,用于存储键-值对中的键和值print("\nKey: "+ key)print("Value:"+ value)
---------------------------------------------------------------------
Key: username
Value:efermiKey: first
Value:enricoKey: last
Value:fermi
  • 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys()://方法key()print(name.title())
------------------------------------------------------
Jen
Sarah
Edward
Phil
  • 按顺序遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):print(name.title())
---------------------------------------------------
Edward
Jen
Phil
Sarah

-遍历字典所有值

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}for language in set(favorite_languages.values()):#values()遍历字典所有值 对包含重复列表调用set()print(language.title())
-------------------------------------------------------------
C
Ruby
Python

-在字典中存储字典

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())
---------------------------------------------------------------------------
Username: aeinsteinFull name: Albert EinsteinLocation: PrincetonUsername: mcurieFull name: Marie CurieLocation: Paris

课后习题

在这里插入图片描述

message = {'first_name':'Lily','last_name':'Z','age':'22','city':'HangZhou'}
print(message['first_name'])
print(message['last_name'])
print(message['age'])
print(message['city'])
--------------------------------------------------------------------------
Lily
Z
22
HangZhou

在这里插入图片描述

favorite_num = {'a':'1','b':'2','c':'3','d':'4','e':'5'}
print("a favorite number is "+favorite_num['a']+".")
print("b favorite number is "+favorite_num['b']+".")
print("c favorite number is "+favorite_num['c']+".")
print("d favorite number is "+favorite_num['d']+".")
print("e favorite number is "+favorite_num['e']+".")
-------------------------------------------------------------
a favorite number is 1.
b favorite number is 2.
c favorite number is 3.
d favorite number is 4.
e favorite number is 5.

在这里插入图片描述

glossary = {'string':'A series of characters.','comment':'A nnote in a program that the Python interpreter ignores.','list':'A collectio of items in a particular order.','loop':'Work through a collection of items,one at a time.','dictionary':'A collection of Key-value pairs.',
}word = 'string'
print("\n"+word.title()+": "+glossary[word])word = 'comment'
print("\n"+word.title()+": "+glossary[word])word = 'list'
print("\n"+word.title()+": "+glossary[word])word = 'loop'
print("\n"+word.title()+": "+glossary[word])word = 'dictionary'
print("\n"+word.title()+": "+glossary[word])
----------------------------------------------------------------------
String: A series of characters.Comment: A nnote in a program that the Python interpreter ignores.List: A collectio of items in a particular order.Loop: Work through a collection of items,one at a time.

在这里插入图片描述

glossary = {'string':'A series of characters.','comment':'A nnote in a program that the Python interpreter ignores.','list':'A collectio of items in a particular order.','loop':'Work through a collection of items,one at a time.','dictionary':'A collection of Key-value pairs.',
}
for word , definition in glossary.items():print("\n"+ word.title()+":"+definition)--------------------------------------------------------------------------String:A series of characters.Comment:A nnote in a program that the Python interpreter ignores.List:A collectio of items in a particular order.Loop:Work through a collection of items,one at a time.Dictionary:A collection of Key-value pairs.

在这里插入图片描述

rivers = {'nile':'rgypt','mississippi':'Us','fraser':'Canada','yangtze':'China',
}for river,country in rivers.items():print("The "+river.title()+" flowa through "+country.title()+".")print("\n The following rivers are included in this data set:")
for river in rivers.keys():print("- "+river.title())
--------------------------------------------------------------------------
The Nile flowa through Rgypt.
The Mississippi flowa through Us.
The Fraser flowa through Canada.
The Yangtze flowa through China.The following rivers are included in this data set:
- Nile
- Mississippi
- Fraser
- Yangtze

在这里插入图片描述

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():print(name.title() + "'s favorite language is " +language.title() + ".")names = ['jen','sarah','ben','lily']
for name in names:if name in favorite_languages.keys():print("thank u,"+name.title()+"!")else:print("weclome,"+name.title()+"!")
----------------------------------------------------------
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.
thank u,Jen!
thank u,Sarah!
weclome,Ben!
weclome,Lily!

在这里插入图片描述

message_01 = {'first_name':'Lily','last_name':'Z','age':'22','city':'HangZhou'}
message_02 = {'first_name':'Ben','last_name':'S','age':'10','city':'ShenZhen'}
message_03 = {'first_name':'Cat','last_name':'F','age':'30','city':'BeiJin'}peoples = [message_01,message_02,message_03]for people in peoples:print(people)
-----------------------------------------------------------------------------------------
{'first_name': 'Lily', 'last_name': 'Z', 'age': '22', 'city': 'HangZhou'}
{'first_name': 'Ben', 'last_name': 'S', 'age': '10', 'city': 'ShenZhen'}
{'first_name': 'Cat', 'last_name': 'F', 'age': '30', 'city': 'BeiJin'}

在这里插入图片描述

#Make an empty ;ist to store the pets in.
pets = []#Make individual pets, and store each one on the list.
pet = {'animal type':'python','name':'john','owner':'guido','eats':'bugs',
}
pets.append(pet)pet = {'animal type':'chicken','name':'ben','owner':'tiffy','eats':'seeds',
}
pets.append(pet)pet = {'animal type':'dog','name':'peo','owner':'eric','weight':37,'eats':'shoes',
}
pets.append(pet)#dispaly information about each pet
for pet in pets:print("\nHere's what I know about "+pet['name'].title()+":")for key,value in pet.items():print("\t"+key+":"+str(value))
-------------------------------------------------------------------------------
Here's what I know about John:animal type:pythonname:johnowner:guidoeats:bugsHere's what I know about Ben:animal type:chickenname:benowner:tiffyeats:seedsHere's what I know about Peo:animal type:dogname:peoowner:ericweight:37eats:shoes

在这里插入图片描述

favorite_places = {'eric':['bear mountain','death valley','tierra del fuego'],'erin':['hawaii','iceland'],'ever':['mt.verstovavua','the playfround','south carolina']
}for name,places in favorite_places.items():print("\n"+name.title()+" likes the following places:")for place in  places:print("-"+place.title())
---------------------------------------------------------------
Eric likes the following places:
-Bear Mountain
-Death Valley
-Tierra Del FuegoErin likes the following places:
-Hawaii
-IcelandEver likes the following places:
-Mt.Verstovavua
-The Playfround
-South Carolina

在这里插入图片描述

favorite_numbers = {'mandy':[42,17],'micah':[23,33,44],'gus':[3,4],
}for  name,numbers in favorite_numbers.items():print("\n"+name.title()+" likes the following numbers:")for number in numbers:print(" "+str(number))
-----------------------------------------------------------------------Mandy likes the following numbers:4217Micah likes the following numbers:233344Gus likes the following numbers:34

在这里插入图片描述

cities = {'santiago':{'country':'chile','population':33333333,'nearby mountains':'andes',},'talkrren':{'country':'aksd','population':4535432445,'nearby mountains':'skjdjd',},'hausdueh':{'country':'dsdsf','populartion':3423544543,'nearby mountains':'fdsfsd',},
}for city ,city_info in cities.items():country = city_info['country'].title()population = city_info['country'].title()mountains = city_info['nearby mountains'].title()print("\n"+city.title()+" is in "+country +".")print(" it has a population of about "+str(population)+".")print("The "+mountains+"mountains are nearby.")
-----------------------------------------------------------------------
Santiago is in Chile.it has a population of about Chile.
The Andesmountains are nearby.Talkrren is in Aksd.it has a population of about Aksd.
The Skjdjdmountains are nearby.Hausdueh is in Dsdsf.it has a population of about Dsdsf.
The Fdsfsdmountains are nearby.

在这里插入图片描述

这篇关于chapter6 字典的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/766283

相关文章

POJ2001字典树

给出n个单词,求出每个单词的非公共前缀,如果没有,则输出自己。 import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;

python 实现第k个字典排列算法

第k个字典排列算法介绍 "第k个字典排列"算法通常指的是在给定的字符集合(例如,字符串中的字符)中,找到所有可能排列的第k个排列。这个问题可以通过多种方法解决,但一个常见且高效的方法是使用“下一个排列”算法的变种,或称为“第k个排列”的直接算法。 方法一:使用“下一个排列”的变种 生成所有排列:首先生成所有排列,但显然这种方法对于较大的输入集合是不切实际的,因为它涉及到大量的计算和存储。 排序

POJ3617(字典序最小问题)

书中43页 此题有坑点,PE了40分钟.也是醉了....题目要求每80个字符才换行,而且最后一个如果恰好就不用换,这不是无聊嘛....... #include <iostream>#include <cstdio>#include <cstring>using namespace std;int n,m;char S[2100],P[2100];int main(){#ifd

POJ 2001 Shortest Prefixes(字典树入门)

题目: http://poj.org/problem?id=2001 题意: 找到多个字符串中,各自唯一的最短子串,例如 carte 与 carce 各自唯一的最短子串为cart与carc,即不会与其它字符串的子串重复。 思路: 字典树 解题心得: 更新关键值的时机很重要 代码: #include<stdio.h>#include<string>typedef str

Oracle数据库(数据字典、表空间、表的创建、视图)

知识点引用: http://www.2cto.com/database/201207/142874.html http://blog.csdn.net/haiross/article/details/11772847 一. 彻底卸载Oracle 方式1、重装操作系统 方式2、 2.1 DBCA删除数据库开始 → 程序 → Oracle → 开发与移植工具 → Datab

Python的字符串,list,tuple,set,字典操作详解

1.字符串python是要创建成字符串的元素,其中的每个字母都是单一的子串,把它放在' '单引号或是'' ''引号中,就完成了python 字符串的创建。#str强制转换>>> a=123>>> b=str(a) #将整数转化为字符串>>> b'123'>>> a=[1,2,3]>>> b=str(a) #将list转化为字符串>>> b'[1, 2, 3]'#字符串下

OC中数组、字典、集合常用方法的运用

/* ====================== 一 NSArray========================          1.创建对象          1.1初始化方法(2) //一般程序有问题先检查初始化          1.2类方法          1.3字面量方法          2.数组查找          2.1通过下标访问对象[ .[i]]

python pickle 模块用于保存python内存数据(包括实例对象、字典、列表等所有python中的数据)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言基本用法 前言 Python 的 pickle 模块用于序列化和反序列化 Python 对象。这意味着你可以将 Python 对象(如列表、字典、类实例等)转换为字节流(序列化),并将其保存到文件中或在网络上传输,然后在需要的时候将其恢复为原始 Python 对象(反序列化)。 常见用途

Python 从入门到实战8(字典)

我们的目标是:通过这一套资料学习下来,通过熟练掌握python基础,然后结合经典实例、实践相结合,使我们完全掌握python,并做到独立完成项目开发的能力。       上篇文章我们通过举例学习了python 中元组的定义及相关操作。今天详细讲述字典的定义及相关的操作,也是经常使用到的。 1、字典的定义 字典是由{}括住的,内容以“键-值对”的形式存储的无序序列。 字典的主要特点如下:

Python 字典详解

Python 字典 : 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示: d = {key1 : value1, key2 : value2 } 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 一个简单的