Python 学习笔记

1.使用字典

字典 是一系列键-值对。

* 每个键都与一个值相关联,你可以使用键来访问与之相关联的值。
* 与键相关联的值可以是数字、字符串、列表乃至字典。
* 事实上,可将任何Python对象用做字典中的值。
* 字典用放在花括号 {} 中的一系列键-值对表示。

      例如: alien = {'color': 'green', 'point': 5}

* 键和值之间用冒号分隔,键-值对之间用逗号分隔。
* 字典通常用来存储一个对象的多种信息,也可用来存储众多对象的同一种信息。

2.访问字典中的值

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

要获取与键相关联的值,可依次指定字典名和放在方括号内的键。

3.添加键-值对

要添加键-值对,可依次指定字典名,用方括号括起来的键和相关联的值。

>>> alien['x_position'] = 0
>>> print(alien)
{'color': 'green', 'point': 5, 'x_position': 0}

注:键-值对的顺序与添加顺序不同。Python不关心键-值对的添加顺序,只关心键和值之间的关联关系。

4.修改字典中的值

要修改字典中的值,可依次指定字典名,用方括号括起的键以及与该键相关联的新值。


>>> alien = {'color': 'green'}
>>> print(alien)
{'color': 'green'}
>>> alien['color'] = 'red'
>>> print(alien)
{'color': 'red'}

5.删除字典中的值

可使用 del 语句将相应的键-值对彻底删除。使用 del 语句时,必须指定字典名和要删除的值。

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

注:删除的键-值对永远消失了。所以删除前一定做好判断和备份。

6.遍历字典

6.1.遍历字典中的所有的键-值对(for)

user = {
    'username': 'dylan',
    'first': 'fdylan',
    'last': 'ldylan',
    }

for key, value in user.items():
    print("
Key: " + key)
    print("Value: " + value)


Key: username
Value: dylan

Key: first
Value: fdylan

Key: last
Value: ldylan

方法 items() 返回一个键-值对列表,for 循环依次将每个键-值对存储到指定的两个变量中,这两个变量可以是任何名称。

6.2.遍历字典中的所有键

>>> for key in user.keys():
         print("
Key: " + key)

Key: username

Key: first

Key: last

方法 keys() 返回字典中键的列表。遍历字典时,会默认遍历所有的键列表,所以如果只取字典中的键,不用方法 keys() 也可以。如下:

>>> for key in user:
         print("
Key: " + key)

Key: username

Key: first

Key: last

6.3.按顺序遍历字典中的所有键(sorted())

>>> for key in sorted(user.keys()):
               print("
Key: " + key)

Key: first

Key: last

Key: username

6.4.遍历字典中的所有值

>>> for value in user.values():
    print('Value: ' + value)

Value: dylan
Value: fdylan
Value: ldylan

方法 values() 返回字典中值的列表。为了避免取出的键或者值列表中有重复的数据,可以用 set() 方法来去掉重复。

>>> rivers = {
    'yangtse': 'china',
    'yangtse': 'china',
    'nile': 'africa',
    'amazon': 'brazil',
    'amazon': 'peru',
    }
>>> for value in set(rivers.values()):
    print('Value:' + value)

Value:africa
Value:china
Value:peru
原文地址:https://www.cnblogs.com/objmodel/p/7655108.html