Python 笔记- dictionary

  1. 定义:
    定义在花括号 {} 中的一系列无序的,非重复键的键值对的集合。
alien = {'color': 'green', 'points': 5}

字典中多个元素以逗号分隔。

通过 dict() 函数可以直接从一个键值对列表中构造一个字典:

>>> alien_property = [('color', 'green'), ('points', 5)]
>>> alien = dict(alien_property)
>>> print(alien)
{'color': 'green', 'points': 5}

字典的键可以是任意不可变量,如字符串、数字或者元组,如果带构造的字典的所有键均为字符串,可以使用下面形式进行构造:

>>> alien = dict(color='green', point=5)
>>> print(alien)
{'color': 'green', 'point': 5}
>>> 
  1. 访问字典中的元素:
    a. 通过键访问指定元素:
>>> print(alien['color'])
green

b. 遍历字典:
1)使用 items() 方法遍历所有键值对:

>>> print(alien.items())
dict_items([('points', 5), ('x_position', 0), ('y_position', 25)])
>>>
>>> for key, value in alien.items():
...     print("Key: " + key, "\nValue: " + str(value), "\n")
... 
Key: points 
Value: 5 

Key: x_position 
Value: 0 

Key: y_position 
Value: 25 

2)使用 keys() 方法遍历所有键:

>>> print(alien.keys())
dict_keys(['points', 'x_position', 'y_position'])
>>> 
>>> for key in alien.keys():
...     print(key)
... 
points
x_position
y_position

实际上下面的写法也可以获取所有键:

>>> for key in alien:
...     print(key)
... 
points
x_position
y_position

但是显示调用 keys() 方法可以让代码更容易理解
通过 list 构造只包含键的列表:

>>> list(alien)
['points', 'x_position', 'y_position']

3)使用 values() 遍历所有值:

>>> print(alien.values())
dict_values([5, 0, 25, 4])
>>>
>>> for value in alien.values():
...     print(value)
... 
5
0
25
4

使用 set() 函数可以遍历所有非重复值:

>>> alien['x_position'] = 5
>>> print(alien)
{'points': 5, 'x_position': 5, 'y_position': 25, 'lives': 4}
>>> print(set(alien.values()))
{25, 4, 5}

【注】键是不可重复的,但值没有此约束。

  1. 字典元素增删改:
    a. 新增元素
    新增一对键值:
>>> alien['x_position'] = 0
>>> alien['y_position'] = 25
>>> print(alien)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

b. 修改元素:

>>> alien['color'] = 'yellow'
>>> print(alien['color'])
yellow

c. 删除元素, 使用 del 语句:

>>> del alien['color']
>>> print(alien)
{'points': 5, 'x_position': 0, 'y_position': 25}
  1. 排序:
    使用 sorted() 函数对字典进行顺序输出:
>>> alien['lives'] = 4
>>>> for key in sorted(alien):
...     print('Key: ' + key, '\nValue: ' + str(alien[key]), '\n')
... 
Key: lives 
Value: 4 

Key: points 
Value: 5 

Key: x_position 
Value: 0 

Key: y_position 
Value: 25 

同样可以通过设置 reverse=True 来反序输出:


>>> for key in sorted(alien, key = None, reverse = True):
...     print('Key: ' + key, '\nValue: ' + str(alien[key]), '\n')
... 
Key: y_position 
Value: 25 

Key: x_position 
Value: 0 

Key: points 
Value: 5 

Key: lives 
Value: 4 
  1. 输出非重复的所有值:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值