Python学习(六)字典

Python 字典

Python 字典:是一系列的键与值得对,与键相关联的值可以是数字,字符串,列表乃至字典。

Python中字典用放在花括号{} 中的一系列的键与值对表示

如:alien_0 = {'color': 'green'}

创建一个字典

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

{'color': 'green', 'points': 5}

访问字典中的值

alien_0 = {'color': 'green', 'points': 5}

print(alien_0['color'])

print(alien_0['points'])

green

5

添加键-值对

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

{'color': 'green', 'points': 5}

alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)

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

修改字典中的值

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)

alien_0['y_position'] = 180

print(alien_0)

{'color': 'green', 'points': 5}

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

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

删除键-值对

alien_0 = {'color': 'green', 'points': 5}

print(alien_0)

alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)

alien_0['y_position'] = 180

print(alien_0)

del alien_0['color']

print(alien_0)

{'color': 'green', 'points': 5}

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

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

{'points': 5, 'x_position': 0, 'y_position': 180}

注意:删除键-值对永远消失!!!

由类似对象组成的字典

Python 字典.items() 方法以列表返回可遍历的(键, 值) 列表。

favorite_languages.items()

Python 字典.keys() 方法以列表返回可遍历的(键) 列表。

favorite_languages.keys()

Python 字典.values() 方法以列表返回可遍历的(值) 列表。

favorite_languages.values()

Python sorted(字典.values()) 按顺序方法以列表返回可遍历的(值) 列表。

sorted(favorite_languages.values)

Python set(字典.values()) 列表去重方法以列表返回可遍历的(值) 无重复值列表。

set(favorite_languages.values)

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python',

}

for name, language in favorite_languages.items():

print("%s's favorite language is %s ."  %(name.title(),language.title()))
Jen's favorite language is Python .

Sarah's favorite language is C .

Edward's favorite language is Ruby .

Phil's favorite language is Python .

嵌套

字典列表

# Make an empty list for storing aliens.创建空字典
aliens = []

# Make 30 green aliens.添加字典列表
for alien_number in range (0,30):
    if alien_number > 3 and alien_number < 6 :
        new_alien = {'color': 'yellow', 'points': 5, 'speed': 'slow'}
        aliens.append(new_alien)
    else:
        new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
        aliens.append(new_alien)
    print('====>>:%s'%(alien_number))
print(len(aliens))

#修改外星人战斗力
for alien in aliens[0:6]:
#颜色green的移动速度10
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
#颜色red移动速度15
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15
        
# Show the first 5 aliens:
for alien in aliens[0:7]:
    print(alien)
print

结果

====>>:0
...
====>>:29
30
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

字典中存储列表

# Store information about a pizza being ordered.
#存储所点披萨的信息
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }

# Summarize the order.
#概述披萨信息
print("You ordered a %s-crust pizza with the following toppings:" %(pizza['crust']))

for topping in pizza['toppings']:
    print("	%s"%(topping))
  
#执行结果    
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("
Username: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']

    print("	Full name: " + full_name.title())
    print("	Location: " + location.title())

#执行结果

Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris
原文地址:https://www.cnblogs.com/jorbabe/p/8593334.html