python编程 从入门到实践——第6章 字典

目录

1. 使用字典

1.1 访问字典中的值

1.2 添加键-值对

1.3 先创建一个空字典

1.4 修改字典中的值

1.5 删除键-值对 del语句

1.6 由类似对象组成的字典

2. 遍历字典

2.1 遍历所有的键-值对 items()方法

2.2 遍历字典中所有键 keys()方法

2.3 按顺序输出字典中所有键 sorted(dictionary.keys())

2.4 遍历字典中的所有值 values()方法

3. 嵌套


1. 使用字典

字典是一系列 键-值 对。每个键都与一个值相关联,可以通过键访问相关的值。

与键相关的值可以使数字、字符串、列表、字典,事实上,可以将任何python对象用作字典中的值

字典使用花括号{ }表示。

alien_o = {"color" : "green", "point" : 5}

1.1 访问字典中的值

alien_0 = {"color" : "green", "point" : 5}

print(alien_0["color"])

1.2 添加键-值对

>>> alien_0 = {"color" : "green", "point" : 5}
>>> print(alien_0)
{'color': 'green', 'point': 5}

#添加x和y坐标位置
>>> alien_0["x_position"]=0   
>>> alien_0["y_position"]=25
>>> print(alien_0)
{'color': 'green', 'point': 5, 'x_position': 0, 'y_position': 25}

1.3 先创建一个空字典

有时候需要新建一个空字典,之后再添加各个键-值对。

>>> alien_0={}
>>> 
>>> alien_0["color"] = "green"
>>> alien_0["point"] = 5
>>> print(alien_0)
{'color': 'green', 'point': 5}

1.4 修改字典中的值

alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original position: " + str(alien_0['x_position']))

# Move the alien to the right.
# Figure out how far to move the alien based on its speed.
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    # This must be a fast alien.
    x_increment = 3

# The new position is the old position 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值