# Create a simple dictionary
alien_0 = {
'color':'green','points':3}
# Dictionary access
print(alien_0['color'])
print(alien_0['points'])
new_point = alien_0['points']
print("you just earned " + str( new_point) + ' points.')
# Add key - Matching value
print(alien_0)
alien_0['xPosition'] = 0
alien_0['yPosition'] = 5
print(alien_0)
green
3
you just earned 3 points.
{‘color’: ‘green’, ‘points’: 3}
{‘color’: ‘green’, ‘points’: 3, ‘xPosition’: 0, ‘yPosition’: 5}
# Create an empty dictionary
alien_1 = {
}
alien_1['color'] = 'yellow'
alien_1['points'] = 10
print(alien_1)
# Change the value in the dictionary
alien_1['color'] = 'red'
print("The alien is now " + alien_1['color'] + ".")
{‘color’: ‘yellow’, ‘points’: 10}
The alien is now red.
alien_0 = {
'x_position':0,'y_position':5,'speed':'fast'}
print("Original position: " + str(alien_0['x_position']))
# Aliens move right
# According to the speed of aliens to determine the moving distance
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 position: 0
New x_position: 3
# Delete key - Matching value
alien_0 = {
'color':'blue','points':10}
print(alien_0)
del alien_0['color']
print(alien_0)
{‘color’: ‘blue’, ‘points’: 10}
{‘points’: 10}
# A dictionary of similar objects ( Such as programming language )
favorite_languages = {
'jen':'python',
'sarah':'c',
'phil':'ruby',
'edward':'java',
}
friends = ['phil','sarah']
for name in favorite_languages:
print(name.title())
if name in friends:
print(" hi "+name.title()+
", I see your favorite language is "+
favorite_languages[name].title()
)
if 'erin' not in favorite_languages:
print("Erin,plase take our pool")
Jen
Sarah
hi Sarah, I see your favorite language is C
Phil
hi Phil, I see your favorite language is Ruby
Edward
Erin,plase take our pool
#### Dictionary list
# Generate an empty list
alien_0 = []
# Generate 100 Alien
for alien_number in range(100):
new_alien = {
'color':'red','points':10,'speed':'medium'}
alien_0.append(new_alien)
for alien in alien_0[:5]:
print(alien)
print("......")
# Show how many aliens have been generated
print("Total number of aliens: "+ str(len(alien_0)))
{‘color’: ‘red’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘red’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘red’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘red’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘red’, ‘points’: 10, ‘speed’: ‘medium’}
…
Total number of aliens: 100
### Nested list in dictionary
pizza = {
'crust':'thick',
'topping':['mushrooms','extra cheese'],
}
print("you ordered a "+
pizza['crust'] + "-crust pizza"+
" with the following toppings:")
for topping in pizza['topping']:
print("\t"+topping)
you ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
### Nested dictionaries in dictionaries
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for user_name,user_info in users.items():
print("\nUserame: " + user_name)
full_name = user_info['first'] + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tlocation: "+ location.title())
Userame: aeinstein
Full name: Alberteinstein
location: Princeton
Userame: mcurie
Full name: Mariecurie
location: Paris
# Movement between lists
unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
# Delete all specified elements
pets = ['dog','cat','fish','cat','bird','cat','dog']
while 'cat' in pets:
pets.remove('cat')
print(pets)
[‘dog’, ‘fish’, ‘bird’, ‘dog’]
# Fill the dictionary with user input
responses = {
}
active = True
while active:
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let annother person response? (yes/no) ")
if repeat == 'no':
active = False
print("\n-----Poll Result-----")
for name,response in responses.items():
print(name + "would like to climb "+ response + " .")
What is your name? Tom
Which mountain would you like to climb someday? Huashan
Would you like to let annother person response? (yes/no)yes
What is your name? Cindy
Which mountain would you like to climb someday? Taishan
Would you like to let annother person response? (yes/no)yes
What is your name? John
Which mountain would you like to climb someday? Xiangshan
Would you like to let annother person response? (yes/no)no
-----Poll Result-----
Tomwould like to climb Huashan .
Cindywould like to climb Taishan .
Johnwould like to climb Xiangshan .
Committed to quantitative stra