十、字典(dictionary)

1、字典

字典可以存储很多信息,数字,字符串,列表,年龄,地址等

字典是一系列键-值对,每个键对应一个值,可以使用键来访问值,值可以是数字、字符串、列表甚至时字典,键值都在花括号{ }中。

1.1、使用字典

1.1.1、访问字典的值

要访问字典的值,字典名+键名即可访问:

# 键值间使用冒号,每对键值间使用逗号分隔
alien_0 = {'color': 'green', 'points': 4} 
print(alien_0['color'])  # 字典名+键名访问值
'green'

new_points = alien_0['points']
print('You just earned ' + str(new_points) + ' points!')
'You just earned 5 points!'

1.1.2、添加键-值对

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

alien_0 = {'color': 'green', 'points': 5}
alien_0['x_position'] = 0  # 添加x、y的坐标
alien_0['y_position'] = 0  # y_position为键,25为值
print(alien_0)

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

1.1.3、创建字典

  • 创建空字典

要声明一个空字典,直接用一个大括号即可

empty = {}
empty = dict()
empty['x'] = 0            # 向字典中添加键值对
empty['y'] = 25
print(empty)
{'x':0, 'y':25}

  • 使用dict()函数创建字典
# 方法1
a = dict(b=0, c=5, d=10)   # 这里键不能添加引号,因为关键字不能为表达式
print(a)
{'b': 0, 'c': 5, 'd': 10}

# 方法2
b = dict((('f', 70), ('c', 20), ('e', 10)))
print(b)
{'f': 70, 'c': 20, 'e': 10}

# 方法3
d = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
print(d)   # zip()函数将2个元组或者列表对应
{'one': 1, 'two': 2, 'three': 3}

# 方法4 使用列表的形式
e = dict([('one', 1), ('two', 2), ('three', 3)])
print(e)
{'one': 1, 'two': 2, 'three': 3}

# 方法5
f = dict({'three':3, 'two':2, 'one':1})
print(f)
{'one': 1, 'two': 2, 'three': 3}
  • 其它方法
# 直接使用花括号加上键值对
a = dict{'one':1, 'two':2, 'three':3}

1.1.4、修改字典中的值

alien_0 = {'color': 'green'}
alien_0['color'] = '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':          # 访问键'speed'的值,判断是快还是慢
    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   # 新的位置= x位置+x_increment移动的距离
print('new x_position: ' + str(alien_0['x_position']))

1.1.5、删除键-值对

对于没有用的的键-值对,可以使用del 语句删除,使用del 语句,要指定字典名和要删除的键名:

alien_0 = {'color': 'yellow'}
del alien_0['color']
print(alien_0)

{}

1.1.6、多行字典键-值对

对于键-值对比较多的字典,可以采用多行编写,这样既美观也易于阅读:

# 这里展示了对于比较长的字典和print函数可以使用多行编写的方法
favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}


print("jen's favorite language is " +
      favorite_language['jen'].title() +
      '.')
jen's favorite language is Python.

1.2、遍历字典

字典可以存储大量数据,python支持遍历字典的所有键-值对、键或值。

1.2.1、遍历所有键-值对

使用for循环遍历所有键-值对,格式为for+键,+值 in 字典名.items()

格式:for key, value in dict_name.items():

s = {'a': 1,
     'b': 2,
     'c': 3,
     }
for key, value in s.items():  # ke和value可以随意取,但是最好取与字典存储信息相关的名字
    print('\n' + key.title() + ': ' + str(value ))

1.2.2、遍历字典的所有键

要遍历字典的所以键可以使用keys()函数:

s = {'a': 1,
     'b': 2,
     'c': 3,
     }

for key in s.keys():
    print(key.title())
    
A
B
C

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

按顺序遍历字典的键,可以使用sorted()函数来获得特定顺序排列的键列表的副本:

favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

for name in sorted(favorite_language.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.

1.2.4、遍历字典中的所有值

遍历所有值可以使用方法values()方法,它返回一个值的列表,不包括任何键。

favorite_language = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

print('The following language have been mentioned:')

for language in favorite_language.values():
    print(language.title())
    
Python
C
Ruby
Python

# 当所有值很多时,就有可能出现很多重复的值,为剔除重复项,可使用集合(set),可保证每个元素独一无二
.....
for language in set(favorite_language.values()):
    print(language.title())
    
Ruby
C
Python

1.3、嵌套

有时需要将一系列字典存储到列表中,或将列表作为值存在字典中,这就是嵌套,可以列表中嵌套字典、字典中嵌套列表甚至字典中嵌套字典。

1.3.1、在列表中存储字典

aliens = []        # 首先创建一个空列表,用于存储外星人
# 创建30个绿色的外星人
for alien_num in range(30):
    new_alien = {'color': 'green', 'speed': 'slow', 'points': 5}
    aliens.append(new_alien)
# 显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print('...')
# 形式创建了多少个外星人
print('Total number of aliens: ' + str(len(aliens)))
print(aliens)

{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
...
Total number of aliens: 30
[{'color': 'green', 'speed': 'slow', 'points': 5}....] # 一个包含30个字典的列表

修改列表中的字典信息,对于python来说,字典中的元素每个都是独立的:

# 将前3个外星人颜色、速度要点修改
aliens = []

for alien_num in range(0, 30):
    new_alien = {'color': 'green', 'speed': 'slow', 'points': 5}
    aliens.append(new_alien)

for alien in aliens[0:3]:       # 增加个if 语句和for循环
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'fast'
        alien['points'] = 10


for alien in aliens[:5]:
    print(alien)
print('...')
print('Total number of aliens: ' + str(len(aliens)))
print(aliens)

1.3.2、字典中存储列表

# 最喜欢的语言
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'java'],
}
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
    Java

pizza = {
    'crust': 'thick',            # 披萨名字
    'toppings': ['mushrooms', 'extra cheese'],       # 配料表
}

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

for topping in pizza['toppings']:
    print('\t' + topping)
    

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

1.3.3、字典中存储字典

users = {                      # 创建一个名为users的字典,2个键,每个键分别对应几个值,每个值都是以字典形式存在
    'lila': {
        'first': 'li',
        'last': 'la',
        'location': 'china',
    },
    'edward li': {
        'first': 'edward',
        'last': 'li',
        'location': 'american',
    },
}

for user_name, user_info in users.items():
    print('\nUsername: ' + user_name)
    full_name = user_info['first'] + user_info['last']
    location = user_info['location']
    print('\tFull name: ' + full_name)
    print('\tLocation: ' + location)
    
Username: lila
    Full name: lila
    Location: china

Username: edward li
    Full name: edwardli
    Location: american

练习题1

# 创建一个名为cities的字典,将三个城市名作为键,每座城市都创建个字典,并在其中包含该城市的国家,人口,有关该城市的事实,并将信息打印出来
cities = {
    'beijing': {
        'country': 'china',                      # 国家
        'population': '21 million',               # 人口
        'fact': 'the Chinese capital',            # 事实是这个国家的首都

    },
    'washington': {
        'country': 'american',
        'population': '646000',
        'fact': 'the capital of the united states',
    },
    'berlin': {
        'country': 'germany',
        'population': '3.47 million',
        'fact': 'the british germany',
    },
}

for city, city_info in cities.items():
    print('\nCity: ' + city.title())
    print('\t' + city_info['country'].title() + '\n\t' + city_info['population'] + '\n\t' + city_info['fact'])
    '''country = city_info['country']     # 下面这些被注释的语句是第二天print语句的详细写法
    population = city_info['population']
    fact = city_info['fact']

    print('\t' + city_info['population'])
    print('\t' + city_info['fact'])'''
 --------------------------------------   
 City: Beijing
    China
    21 million
    the Chinese capital

City: Washington
    American
    646000
    the capital of the united states

City: Berlin
    Germany
    3.47 million
    the british germany

练习2

# 创建个名为favorite_placers的字典,三个人名为键,每个人存储1-3个喜欢的地方,打印出每个人喜欢的地方
favorite_places = {
    'tom': ['beijing', 'xian', 'changsha'],
    'lila': ['shanghai', 'chongqing'],
    'edward': ['chengdu', 'hangzhou'],
}

for name, places in favorite_places.items():              # 遍历字典所有键-值对
  print('\n' + name.title() + 'likes the following places:')
  for place in places:             # 遍历值(列表)
    print('\t' + place)
    
----------------
Tom likes the following places:
    Beijing
    Xian
    Changsha

Lila likes the following places:
    Shanghai
    Chongqing

Edward likes the following places:
    Chengdu
    Hangzhou

你可能感兴趣的:(十、字典(dictionary))