玩命加载中 . . .

python-字典


6.1 一个简单的字典

In [1]:

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

print(alien_0['color'])

print(alien_0['points'])
green
5

6.2.1 访问字典中的值

In [2]:

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

new_points = alien_0['points']

print("You just earned " + str(new_points) + " points!")
You just earned 5 points!

6.2.2 添加键-值对

In [3]:

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

print(alien_0)

#外星人的X坐标和y坐标

alien_0['x_position'] = 0

alien_0['y_position'] = 25

print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

6.2.3 先创建一个空字典

In [4]:

alien_0 = {}

#分行添加各个键值对

alien_0['color'] = 'green'

alien_0['points'] = 5

print(alien_0)
{'color': 'green', 'points': 5}

6.2.4 修改字典中的值

In [5]:

alien_0 = {'color':'green'}

#现在外星人的颜色是

print("The alien is " + alien_0['color'] + ".")

alien_0['color'] = 'yellow'

#修改了外星人的颜色为黄色

print("The alien is now " + alien_0['color'] + ".")
The alien is green.
The alien is now yellow.

In [6]:

#对一个能够以不同速度移动的外星人的位置进行跟踪

#存储外星人的当前速度,并确定该外星人向右移动多远

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}

print("Original x_position: " +s tr(alien_0['x_position']))

#向右移动外星人

#据外星人当前速度决定其移动多远

if alien_0['speed'] == 'slow':

    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

print("New x_position:" + str(alien_0['x_position']))
Original x_position: 0
New x_position:2

6.2.5 删除键-值对

In [7]:

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

print(alien_0)

del alien_0['points']

print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}

6.2.6 由类似对象组成的字典

In [8]:

#调查4个人,询问他们最喜欢的编程语言是什么

favorite_languages = {

    'jen': 'python',

    'sarah': 'c',

    'edward': 'ruby',

    'phil': 'python',  

    }


print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
Sarah's favorite language is C.

6.3 遍历字典

6.3.1 遍历所有的键-值对

In [9]:

user_0 = {

    'username': 'efer',

    'first': 'emrico',

    'last': 'fermi',

}

for key,value in user_0.items():

    print("\nKey: " + key)

    print("Value: " + value)
Key: username
Value: efer

Key: first
Value: emrico

Key: last
Value: fermi

In [10]:

favorite_languages = {

    'jen': 'python',

    'sarah': 'c',

    'edward': 'ruby',

    'phil': 'python',  

    }

for name,language in favorite_languages.items():

    print(name.title() + "'s favorite language is " + 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.

6.3.2 遍历字典中的所有键

In [11]:

favorite_languages = {

    'jen': 'python',

    'sarah': 'c',

    'edward': 'ruby',

    'phil': 'python',  

    }

for name in favorite_languages.keys():

    print(name.title())
Jen
Sarah
Edward
Phil

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

In [12]:

favorite_languages = {

    'jen': 'python',

    'sarah': 'c',

    'edward': 'ruby',

    'phil': 'python',  

    }

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

6.3.4 遍历字典中的所有值

In [13]:

favorite_languages = {

    'jen': 'python',

    'sarah': 'c',

    'edward': 'ruby',

    'phil': 'python',  

    }

print("The following languages have been mentioned: ")

for language in favorite_languages.values():

    print(language.title())
The following languages have been mentioned: 
Python
C
Ruby
Python

6.4 嵌套

6.4.1 字典列表

In [14]:

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

alien_1 = {'color': 'yellow','points':10}

alien_2 = {'color': 'red','points':15}


aliens = [alien_0,alien_1,alien_2]

for alien in aliens:

    print(alien)
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

In [15]:

#创建一个外星人的空列表

aliens = []

#创建30个绿色的外星人

for alien_number in range(30):

    new_alien = {'clolr':'green','points':5,'speed':'slow'}

    aliens.append(new_alien)

#显示前5个外星人

for alien in aliens[:5]:

    print(alien)

print("...")

#显示创建了多少个外星人

print("Total number of aliens: " + str(len(aliens)))
{'clolr': 'green', 'points': 5, 'speed': 'slow'}
{'clolr': 'green', 'points': 5, 'speed': 'slow'}
{'clolr': 'green', 'points': 5, 'speed': 'slow'}
{'clolr': 'green', 'points': 5, 'speed': 'slow'}
{'clolr': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

In [16]:

aliens = []

for alien_number in range(30):

    new_alien = {'color':'green','points':5,'speed':'slow'}

    aliens.append(new_alien)

for alien in aliens[:3]:

    if alien['color'] == 'green':

        alien['color'] = 'yellow'

        alien['speed'] = 'medium'

        alien['points'] = 10

for alien in aliens[:5]:

    print(alien)

print("...")

print("Total number of aliens: " + str(len(aliens)))
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

6.4.2 在字典中存储列表

In [17]:

pizza = {

    'crust': 'thick',

    'toppings': ['mushrooms','extra cheese'],

}

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

for topping in pizza['toppings']:

    print("\t" + topping)
You ordered a thick-crust pizzawith the following toppings:
    mushrooms
    extra cheese

6.4.3 在字典中存储字典

In [18]:

# 多个网站用户,每个用户都有自己独特的用户名,字典里用户名为键

users = {

    'aeinstein':{

        'first': 'albert',

        'last': 'einstein',

        'location': 'princeton',

    },

    'mcurie':{

        'first': 'marie',

        'last': 'curie',

        'location': 'paris',

    },

}

for username,user_info in users.items():

    print("\nUsername: " + username)

    full_name = user_info['first'] + " " + user_info['last']

    location = user_info['location']

    print("\tFull name: " + full_name.title())

    print("\tLocation: " + location.title())
Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton

Username: mcurie
    Full name: Marie Curie
    Location: Paris

文章作者: Edgar
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Edgar !
评论
  目录