-
Notifications
You must be signed in to change notification settings - Fork 0
Chapter 6
Jarlin Almanzar edited this page Oct 28, 2019
·
4 revisions
Def: A collection of key-value pairs. Each key is connect to a value, and you can use a key to access the value associated with that key.
A key can be:
- a number
- a string
- a list
- another dictionary
- any object created in python
A dictionary is wrapped in braces {} and a dynamic structure, thus you can add a new key-value pair at any time.
Dictionaries allow you to connect pieces of related information, can store a limitless amount of information, and model a variety of real-world objects.
alien_o = {"color": "green", "points":5}
print(alien_o["color"])
print(alien_o["points"])
alien_o = {"color": "green", "points":5}
print(alien_o["color"])
print(alien_o["points"])
alien_o["x_position"] = 0
alien_o["y_position"] = 25
print(alien_o)
alien_o = {"color": "green", "points":5}
print(alien_o["color"])
print(alien_o["points"])
alien_o["x_position"] = 0
alien_o["y_position"] = 25
alien_o["color"] = "blue"
print(alien_o)
del dict["name_of_key"]
alien_o = {"color": "green", "points":5}
print(alien_o["color"])
print(alien_o["points"])
alien_o["x_position"] = 0
alien_o["y_position"] = 25
alien_o["color"] = "blue"
del alien_o["points"]
print(alien_o)
Why? What if a key-pair value does not exist in a dictionary
alien_o = {"color": "green", "points":5}
print(alien_o["color"])
print(alien_o["points"])
alien_o["x_position"] = 0
alien_o["y_position"] = 25
alien_o["color"] = "blue"
del alien_o["points"]
point_value = alien_o.get("points", "No point value assigned.")
print(alien_o)
print(point_value)
user = {
"username" : "The_first",
"first" : "Jarin",
"last" : "Almanzar",
}
for key, value in user.items():
print(f"key is {key}")
print(f"value is {value}\n")
fav_lang = {
"jarlin" : "python",
"Cris" : "Java",
"Dante" : "SQL",
"Arvin" : "C",
}
for name, language in fav_lang.items():
print(f"{name}'s favorite language is {language}")
key() returns the keys of a dict
values() returns the values of a dict
values()
fav_lang = {
"jarlin" : "python",
"Cris" : "Java",
"Dante" : "SQL",
"Arvin" : "C",
}
# For keys
for name in fav_lang.keys():
print(name.title())
# For values
for language in fav_lang.values():
print(language.title())
alien_0 = {"color": "green", "points":5}
alien_1 = {"color": "yellow", "points":10}
alien_2 = {"color": "red", "points":10}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
pizza = {
"crust": "thick",
"toppings" : ["mushrooms", "onions", "extra cheese"],
}
print(f"You ordered a {pizza['crust']}-crust pizza")
users = {
"scientist": {
"first" : "albert",
"last" : "einstein",
"location" : "princeton",
},
}
# scientist is the key for alberrt einstein
for username, user_info in users.items():
print(f"\n Username: {username}")
print(f"\n fullname: {user_info['first']} and {user_info['last']}")