《Python编程从入门到实践》学习笔记06字典

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

green
5

alien_0={'color':'green','points':5}
new_points=alien_0['points']
print(f'you just earned {new_points} points!')

you just earned 5 points!

#添加键值对
alien_0={'color':'green','points':5}
print(alien_0)
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}

alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}

alien_0={'color':'green','points':5}
print(f"the alien is {alien_0['color']}")

the alien is green

alien_0['color']='yellow'
print(f"the alien is {alien_0['color']}")

the alien is yellow

alien_0={'x_position':0,
        'y_position':25,
        'speed':'medium'}
print(f"Original x-position:{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(f"New x-position:{alien_0['x_position']}")

Original x-position:0
New x-position:2

#删除键值对
alien_0={'color':'green','points':5}
print(alien_0)

del alien_0['points']
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’}

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

language=favourite_languages['sarah'].title()
print(f"Sarah's favourite language is {language}")

Sarah’s favourite language is C

alien_0={'color':'green','speed':'slow'}
point_value=alien_0.get('points','No points value assigned.')
print(point_value)

No points value assigned.

alien_0={'color':'green','speed':'slow'}
point_value=alien_0.get('points')
print(point_value)

None

#遍历字典
user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi'
}

for a,b in user_0.items():
    print(f'\nKey:{a}')
    print(f'Key:{b}')

Key:username
Key:efermi

Key:first
Key:enrico

Key:last
Key:fermi

#不加item()
user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi'
}

for a,b in user_0:
    print(f'\nKey:{a}')
    print(f'Key:{b}')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_47956\556717232.py in <module>
      6 }
      7 
----> 8 for a,b in user_0:
      9     print(f'\nKey:{a}')
     10     print(f'Key:{b}')

ValueError: too many values to unpack (expected 2)
favourite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

for name,language in favourite_languages.items():
    print(f"{name.title()}'s favourite language is {language.title()}'")

Jen’s favourite language is Python’
Sarah’s favourite language is C’
Edward’s favourite language is Ruby’
Phil’s favourite language is Python’

#keys()
favourite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name in favourite_languages.keys():
    print(name.title())

Jen
Sarah
Edward
Phil

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

friends=['phil','sarah']
for name in favourite_languages.keys():
    print(f'{name.title()}')
    
    if name in friends:
        language=favourite_languages[name].title()
        print(f'\t{name.title()},i see you love {language}!')
Jen
Sarah
	Sarah,i see you love C!
Edward
Phil
	Phil,i see you love Python!
favourite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name in sorted(favourite_languages.keys()):
    print(f'{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

favourite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
print('the following languages have been metioned:')
for language in favourite_languages.values():
    print(language.title())

the following languages have been metioned:
Python
C
Ruby
Python

favourite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
print('the following languages have been metioned:')
for language in set(favourite_languages.values()):
    print(language.title())

the following languages have been metioned:
C
Ruby
Python

alien_0={'color':'green','points':5}
alien_1={'color':'green','points':10}
alien_2={'color':'green','points':15}

aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 10}
{‘color’: ‘green’, ‘points’: 15}

#{'color':'green','points':5,'speed':'slow'}
#{'color':'green','points':5,'speed':'slow'}
#{'color':'green','points':5,'speed':'slow'}
#{'color':'green','points':5,'speed':'slow'}
#{'color':'green','points':5,'speed':'slow'}
#...
#Total number of aliens:30
aliens=[]
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)

for alien in aliens[:5]:
    print(alien)

print('...')
print(f'total number of aliens:{len(aliens)}')

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

total number of aliens:30

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(f'total number of aliens:{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

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
    elif alien['color']=='yellow':
        alien['color']='red'
        alien['speed']='fast'
        alien['points']=15

for alien in aliens[:5]:
    print(alien)

print('...')
print(f'total number of aliens:{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

#在字典中存储列表
pizza={
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
}
print(f"you orderes a {pizza['crust']}-crut pizza with the following toppings:")

for topping in pizza['toppings']:
    print('\t'+topping)
you orderes a thick-crut pizza with the following toppings:
	mushrooms
	extra cheese
favourite_languages={
    'jen':['python','ruby'],
    'sarah':'c',
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}
for name,languages in favourite_languages.items():
    print(f"\n{name.title()}'s favourite languages are:")
    for language in languages:
        print(f'\t{language.title()}')
Jen's favourite languages are:
	Python
	Ruby

Sarah's favourite languages are:
	C

Edward's favourite languages are:
	Ruby
	Go

Phil's favourite languages are:
	Python
	Haskell
users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris'
    },
}

for username,user_info in users.items():
    print(f"\nUsername:{username}")
    full_name=f"{user_info['first']}{user_info['last']}"
    location=user_info['location']
    
    print(f"\tFull name:{full_name.title()}")
    print(f"\tLocation:{location.title()}")
Username:aeinstein
	Full name:Alberteinstein
	Location:Princeton

Username:mcurie
	Full name:Mariecurie
	Location:Paris

你可能感兴趣的:(python,python,笔记)