百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python学习笔记—字典(字典 python)

off999 2024-09-16 00:46 42 浏览 0 评论

# _*_ coding:utf-8 _*_

##########字典############

#一个简单的字典

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!")

-------------------------------------------

green

5

You just earned 5 points!

-------------------------------------------

#添加键-值对

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)

-------------------------------------------

{'color': 'green', 'points': 5}

{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

-------------------------------------------

#先创建一个空字典

alien_0 = {}

alien_0['color'] = 'green'

alien_0['points'] = 5

print(alien_0)

-------------------------------------------

{'color': 'green', 'points': 5}

-------------------------------------------

#修改字典中的值

alien_0 = {'color': 'green', 'points': 5}

print("The alien is " + alien_0['color'] + ".")

alien_0['color'] = 'yellow'

print("The alien is now " + alien_0['color'] + ".")

-------------------------------------------

The alien is green.

The alien is now yellow.

-------------------------------------------

#一个例子:对一个能够以不同速度移动的外星人的位置进行追踪

alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}

print("Original x-position: " + str(alien_0['x_position']))

#向右移动的外星人

#据外星人当前速度决定将其移动多远

if alien_0['speed'] == 'slow':

x_increment = 1

elif alien_0['speed'] == 'medium':

x_increment = 2

else:

x_increment = 3

#新位置等于老位置加上增量

alien_0['x_position'] = alien_0['x_position'] + x_increment

print("New x-position: " + str(alien_0['x_position']))

-------------------------------------------

Original x-position: 0

New x-position: 2

-------------------------------------------

#删除键-值对

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

del alien_0['points']

print(alien_0)

-------------------------------------------

{'color': 'green', 'points': 5}

{'color': 'green'}

-------------------------------------------

#遍历字典

user_0 = {

'username': 'efermi',

'first': 'enrico',

'last': 'fermi',

}

for key, value in user_0.items():

print("\nKey: " + key)

print("Value: " + value)

-------------------------------------------


Key: username

Value: efermi


Key: first

Value: enrico


Key: last

Value: fermi

-------------------------------------------

#遍历字典中的所有键

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

for name in favorite_languages.keys():

print(name.title())

-------------------------------------------

Jen

Sarah

Edward

Phil

-------------------------------------------

#遍历字典时,会默认遍历所有的键

for name in favorite_languages:

print(name.title())

-------------------------------------------

Jen

Sarah

Edward

Phil

-------------------------------------------

#可以用当前键来访问与之相关联的值

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

friends = ['phil', 'sarah']

for name in favorite_languages.keys():

print(name.title())


if name in friends:

print(" Hi " + name.title() + ",I see your favorite language is " + favorite_languages[name].title() + "!")

-------------------------------------------

Jen

Sarah

Hi Sarah,I see your favorite language is C!

Edward

Phil

Hi Phil,I see your favorite language is Python!

-------------------------------------------

#方法keys()并非只能用于遍历;它返回一个列表

if 'erin' not in favorite_languages.keys():

print("Erin, please take our poll!")

-------------------------------------------

Erin, please take our poll!

-------------------------------------------

#按顺序遍历字典中的所有键

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

for name in sorted(favorite_languages.keys()):

print(name.title() + ", thank you for taking the poll.")

-------------------------------------------

Edward, thank you for taking the poll.

Jen, thank you for taking the poll.

Phil, thank you for taking the poll.

Sarah, thank you for taking the poll.

-------------------------------------------

#遍历字典中所有值

favorite_languages = {

'jen': 'Python',

'sarah': 'C',

'edward': 'Ruby',

'phil': 'Python',

}

print("The following languages have been mentioned:")

for language in favorite_languages.values():

print(language.title())

-------------------------------------------

The following languages have been mentioned:

Python

C

Ruby

Python

-------------------------------------------

#为剔除重复项,可使用集合(set)

print("The following languages have been mentioned:")

for language in set(favorite_languages.values()):

print(language.title())

-------------------------------------------

The following languages have been mentioned:

Python

Ruby

C

-------------------------------------------

#嵌套

#字典列表

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)

-------------------------------------------

{'color': 'green', 'points': 5}

{'color': 'yellow', 'points': 10}

{'color': 'red', 'points': 15}

-------------------------------------------

#使用range()生成了30个外星人

#创建一个用于存储外星人的空列表

aliens = []

#创建30个绿色的外星人

for alien_number in range(30):

new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}

aliens.append(new_alien)

#显示前5个外星人

for alien in aliens[:5]:

print(alien)

print("...")

#显示创建了多少个外星人

print("Total number of aliens: " + str(len(aliens)))

-------------------------------------------

{'color': 'green', 'points': 5, 'speed': 'slow'}

{'color': 'green', 'points': 5, 'speed': 'slow'}

{'color': 'green', 'points': 5, 'speed': 'slow'}

{'color': 'green', 'points': 5, 'speed': 'slow'}

{'color': 'green', 'points': 5, 'speed': 'slow'}

...

Total number of aliens: 30

-------------------------------------------

#使用for循环和if语句来修改某些外星人的颜色

#创建一个用于存储外星人的空列表

aliens = []

#创建30个绿色的外星人

for alien_number in range(30):

new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}

aliens.append(new_alien)

for alien in aliens:

if alien['color'] == 'green':

alien['color'] = 'yellow'

alien['speed'] = 'medium'

alien['points'] = 10

elif alien['color'] == 'yellow':

alien['color'] = 'red'

alien['speed'] = 'fast'

alien['points'] = 15


#显示前5个外星人

for alien in aliens[:5]:

print(alien)

print("...")

-------------------------------------------

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

{'color': 'yellow', 'points': 10, 'speed': 'medium'}

...

-------------------------------------------

#在字典中存储列表

#存储所点披萨的信息

pizza = {

'crust': 'thick',

'toppings': ['mushrooms', 'extra cheese'],

}

#概述所点的披萨

print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")

for topping in pizza['toppings']:

print("\t" + topping)

-------------------------------------------

You ordered a thick-crust pizza with the following toppings:

mushrooms

extra cheese

-------------------------------------------

#每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表

favorite_languages = {

'jen': ['Python','Ruby'],

'sarah': ['C'],

'edward': ['Ruby', 'Go'],

'phil': ['Python', 'Haskell'],

}

for name, languages in favorite_languages.items():

print('\n' + name.title() + "'s favorite languages are:")

for language in languages:

print("\t" + language.title())

-------------------------------------------


Jen's favorite languages are:

Python

Ruby


Sarah's favorite languages are:

C


Edward's favorite languages are:

Ruby

Go


Phil's favorite languages are:

Python

Haskell

-------------------------------------------

#在字典中存储字典

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: aeinstein

Full name: Albert Einstein

Location: Princeton


Username: mcurie

Full name: Marie Curie

Location: Paris

-------------------------------------------

相关推荐

无线ap图片(无线ap图标)

WiFi热点中的ap标识即AccessPoint,也就是无线接入点。简单来说就是wifi共享上网中的无线交换机,它是移动终端用户进入有线网络的接入点,主要用于家庭宽带、企业内部网络部署等,可以使无线...

路由器初始密码忘了怎么办(路由器忘记原始密码怎么办)

路由器密码忘了可以通过恢复出厂设置重新设置密码1、把所有网线都从路由器上拔掉,只保留电源线既可;    2、然后用稍尖的笔尖刺紧路由器背面的“RESET”小孔不放;    3、有的是“RESET”...

hotmail邮箱还能用吗(hotmail邮箱登录有手机客户端的吗)

这个是可以重新申请的呢除了谷歌国内受限,其他基本都可以正常使用。看个人使用习惯可自主申请相应邮箱:微软outlook、hotmail邮箱;网易邮箱、网易126邮箱;新浪邮箱、阿里邮箱;QQ邮箱、搜狐...

怎么建立局域网(怎么建立局域网内其他电脑文件夹的快捷方式)
  • 怎么建立局域网(怎么建立局域网内其他电脑文件夹的快捷方式)
  • 怎么建立局域网(怎么建立局域网内其他电脑文件夹的快捷方式)
  • 怎么建立局域网(怎么建立局域网内其他电脑文件夹的快捷方式)
  • 怎么建立局域网(怎么建立局域网内其他电脑文件夹的快捷方式)
diskdigger官网入口(diskinfo官网)

打开LaunchCenterPro,创建一个叫Omnifocus的操作组,然后再往这个操作组添加新的操作。如果你要在Omnifocus创建新收件箱项,添加URL到LaunchCenter...

最新英特尔处理器排名(最新英特尔处理器排名第几)

一、英特尔酷睿i7670。这款英特尔CPU采用的是超频新芯,最大程度的提升处理器的超频能力。二、英特尔酷睿i74790kCPU:这款CPU采用22纳米制程工艺的框架,它的默认频率是4.0到4.4Ghz...

电脑怎样激活win10系统(电脑怎么激活window10)
  • 电脑怎样激活win10系统(电脑怎么激活window10)
  • 电脑怎样激活win10系统(电脑怎么激活window10)
  • 电脑怎样激活win10系统(电脑怎么激活window10)
  • 电脑怎样激活win10系统(电脑怎么激活window10)
nvidia旧版本驱动下载(nvidia新版本驱动)
nvidia旧版本驱动下载(nvidia新版本驱动)

没法装,n卡本身不具备装旧版驱动的功能一、首先在本机电脑内鼠标左键双击打开“驱动人生”(若电脑上无此软件,可以在各大软件市场内下载安装)。二、打开驱动人生软件后,点击“立即体检”进行驱动扫描。三、驱动扫描完成后,点击显卡右边的“箭头”打开驱...

2025-12-18 20:51 off999

怎么解开别人的wifi密码(如何解开别人的wifi密码)

别人的无线网络密码是很不容易破解的,如果人家是愿意分享的,可以在手机上下载"Wifi万能钥匙"注册登陆成功后连接其无线wifi1、以现有的技术手段,是没有办法破解WPA的加密方式(现在...

电脑突然关机(电脑突然关机像断电了一样 再也打不开)
电脑突然关机(电脑突然关机像断电了一样 再也打不开)

如果是插电源的电脑开着突然就关机了,可能是线路接触不良或者是没电了,导致的开着就关机了,如果是你的电脑是充电的那一种可能是你的电池的电量用完了或者是电池的线路接触不良导致的开着突然就关机了,你可以排查一下线路。1、如果你使用的是笔记本电脑,...

2025-12-18 19:51 off999

win7重装系统一直反复重启(win7重装系统无限重启)

WIN7的系统装重复了,可以将原安装的系统删除,方法如下:1、如果以前的windows是安装在C盘上的话,点击桌面上的计算机,选中C盘,鼠标右键选择属性;2、点磁盘清理;3、点清理系统文件,点确定;4...

电脑如何格式化sd卡(电脑格式化sd卡,提示写有保护)

要在电脑上格式化SD卡,可以按照以下步骤:1.将SD卡插入计算机的SD卡读卡器中。2.打开“我的电脑”或“此电脑”,找到SD卡在计算机上的驱动器号(比如E盘)。3.右键单击SD卡驱动器,选择“格...

系统检测不到机械硬盘(系统检测不到机械硬盘怎么办)

第一,我们需要确认一下机械硬盘是否连接正常。可以检查一下硬盘的电源线和数据线是否插紧,是否松动或者断开。如果发现有松动或者断开的情况,可以重新插上并确保插紧。如果硬盘连接正常,但电脑仍然无法读取,那么...

路由器管理平台登录(路由器管理平台登录网址)

路由器的用户登录入口地址是:tplogin.cn电信运营商定制款登录地址是:192.168.2.1或者192.168.8.12、华为(容易)路由器华为路由器跟荣耀路由器只有IP地址,没有域名,它是...

directx修复(DirectX修复工具官网下载)

使用DirectX修复工具很简单。首先需要下载并安装工具,然后打开工具并按照界面提示进行操作即可。工具的作用是自动检测系统中可能存在的DirectX问题,并尝试修复它们,从而保证计算机游戏等应用程序的...

取消回复欢迎 发表评论: