python基础:操作字典

1、遍历整个字典的键-值对

items()方法返回一个键-值对列表,for 循环依次将每个键—值对存储到指定的两个变量中。

使用元组和列表遍历方法遍历字典:

user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
	print("\nKey: " + key)
	print("Value: " + value)

python返回:


Key: last
Value: fermi

Key: first
Value: enrico

Key: username
Value: efermi

2、遍历字典中的所有键

keys()方法返回一个键列表,for 循环依次将每个键存储到指定的变量中。

遍历所有键:

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
	print(name.title())

python返回:

Jen
Sarah
Phil
Edward

备注:keys()方法返回值是列表,所以可以进行sorted排序,下面的values()方法一样。

3、遍历字典中的所有值

values()方法返回一个值列表,for 循环依次将每个值存储到指定的变量中。

遍历所有值:

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in favorite_languages.values():
	print(language.title())

python返回:

Python
C
Python
Ruby

备注:keys()方法返回值是列表,所以可以进行sorted排序,下面的values()方法一样。

4、嵌套

正如列表的元素可以是列表一样,列表的元素也可以是字典;字典的值可以是列表,也可以是字典(字典的值可以是列表或字典,但键不可以是列表或字典)。

列表元素是字典:

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)

python返回:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

字典的值是列表:

# 存储所点比萨的信息
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)

python返回:

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

字典的值是字典:

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

python返回:


Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris

备注:直接调用时,调用方法相当于二维数组users[mcurie][first]

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dunkle.T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值