Dictionaries Flashcards

(18 cards)

1
Q

Can you overwrite values?

A

yes. The same as JS. menu = { “oatmeal” : 3 , “avocado toast” : 6 , “carrot juice” : 5 , “blueberry muffin” : 2 } menu [ “oatmeal” ] = 5 print( menu ) This would yield: { “oatmeal” : 5 , “avocado toast” : 6 , “carrot juice” : 5 , “blueberry muffin” : 2 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you access the values of a dictionary?

A

building_heights = {“Burj Khalifa”: 828, “Shanghai Tower”: 632, “Abraj Al Bait”: 601, “Ping An”: 599, “Lotte World Tower”: 554.5, “One World Trade”: 541.3} >>> building_heights[“Burj Khalifa”] 828 >>> building_heights[“Ping An”] 599

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you search for a key:value in a dictionary?

A

Dictionaries have a .get() method to search for a value instead of the my_dict[key] notation we have been using. If the key you are trying to .get() does not exist, it will return None by default. building_heights = {“Burj Khalifa”: 828, “Shanghai Tower”: 632, “Abraj Al Bait”: 601, “Ping An”: 599, “Lotte World Tower”: 554.5, “One World Trade”: 541.3} #this line will return 632: building_heights.get(“Shanghai Tower”) #this line will return None: building_heights.get(“My House”) You can also specify a value to return if the key doesn’t exist. For example, we might want to return a building height of 0 if our desired building is not in the dictionary. >>> building_heights.get(‘Shanghai Tower’, 0) 632 >>> building_heights.get(‘Mt Olympus’, 0) 0 >>> building_heights.get(‘Kilimanjaro’, ‘No Value’) ‘No Value’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you add a key to a dictionary?

A

To add a single key: value pair to a dictionary, we can use the syntax:

dictionary[key] = value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you add multiple keys?

A

If we wanted to add multiple key : value pairs to a dictionary at once, we can use the .update() method.

Looking at our sensors object from a previous exercise:

sensors = {“living room”: 21, “kitchen”: 23, “bedroom”: 20}
If we wanted to add 3 new rooms, we could use:

sensors.update({“pantry”: 22, “guest room”: 25, “patio”: 34})
This would add all three items to the sensors dictionary.

Now, sensors looks like:

{“living room”: 21, “kitchen”: 23, “bedroom”: 20, “pantry”: 22, “guest room”: 25, “patio”: 34}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you delete a key:value pair from a dictionary?

A

.pop() works to delete items from a dictionary, when you know the key value. Just like with .get(), we can provide a default value to return if the key does not exist in the dictionary.

> > > raffle.pop(320291, “No Prize”)
“Gift Basket”
raffle
{223842: “Teddy Bear”, 872921: “Concert Tickets”, 412123: “Necklace”, 298787: “Pasta Maker”}
raffle.pop(100000, “No Prize”)
“No Prize”
raffle
{223842: “Teddy Bear”, 872921: “Concert Tickets”, 412123: “Necklace”, 298787: “Pasta Maker”}
raffle.pop(872921, “No Prize”)
“Concert Tickets”
raffle
{223842: “Teddy Bear”, 412123: “Necklace”, 298787: “Pasta Maker”}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you get all items?

A

You can get both the keys and the values with the .items() method. Like .keys() and .values(), it returns a dict_list object. Each element of the dict_list returned by .items() is a tuple consisting of:

(key, value)
so to iterate through, you can use this syntax:

biggest_brands = {“Apple”: 184, “Google”: 141.7, “Microsoft”: 80, “Coca-Cola”: 69.7, “Amazon”: 64.8}

for company, value in biggest_brands.items():
print(company + “ has a value of “ + str(value) + “ billion dollars. “)
which would yield this output:

Apple has a value of 184 billion dollars.
Google has a value of 141.7 billion dollars.
Microsoft has a value of 80 billion dollars.
Coca-Cola has a value of 69.7 billion dollars.
Amazon has a value of 64.8 billion dollars.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you get all the values of a dictionary?

A

Dictionaries have a .values() method that returns a dict_values object (just like a dict_keys object but for values!) with all of the values in the dictionary. It can be used in the place of a list for iteration:

test_scores = {“Grace”:[80, 72, 90], “Jeffrey”:[88, 68, 81], “Sylvia”:[80, 82, 84], “Pedro”:[98, 96, 95], “Martin”:[78, 80, 78], “Dina”:[64, 60, 75]}

for score_list in test_scores.values():
print(score_list)

will yield:

[80, 72, 90]
[88, 68, 81]
[80, 82, 84]
[98, 96, 95]
[78, 80, 78]
[64, 60, 75]

There is no built-in function to get all of the values as a list, but if you really want to, you can use:

list(test_scores.values())
However, for most purposes, the dict_values object will act the way you want a list to act.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you get all keys from a dictionary?

A

Sometimes we want to operate on all of the keys in a dictionary. For example, if we have a dictionary of students in a math class and their grades:

test_scores = {“Grace”:[80, 72, 90], “Jeffrey”:[88, 68, 81], “Sylvia”:[80, 82, 84], “Pedro”:[98, 96, 95], “Martin”:[78, 80, 78], “Dina”:[64, 60, 75]}

We want to get a roster of the students in the class, without including their grades. We can do this with the built-in list() function:

> > > list(test_scores)
[“Grace”, “Jeffrey”, “Sylvia”, “Pedro”, “Martin”, “Dina”]

Dictionaries also have a .keys() method that returns a dict_keys object. A dict_keys object is a view object, which provides a look at the current state of the dictionary, without the user being able to modify anything. The dict_keys object returned by .keys() is a set of the keys in the dictionary. You cannot add or remove elements from a dict_keys object, but it can be used in the place of a list for iteration:

user_ids = {“teraCoder”: 100019, “pythonGuy”: 182921, “samTheJavaMaam”: 123112, “lyleLoop”: 102931, “keysmithKeith”: 129384}
users=user_ids.keys()
print(users)

> > > Output:
dict_keys([‘teraCoder’, ‘pythonGuy’, ‘samTheJavaMaam’, ‘lyleLoop’, ‘keysmithKeith’])
for student in test_scores.keys():
print(student)

will yield:

Grace
Jeffrey
Sylvia
Pedro
Martin
Dina

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you loop through a dictonary?

A

for key, value in my_dict.items():
… do something with key or value …

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you use try/except?

A

key_to_check = “Landmark 81” try: print(building_heights[key_to_check]) except KeyError: print(“That key doesn’t exist!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are invalid keys?

A

We can have a list or a dictionary as a value of an item in a dictionary, but we cannot use these data types as keys of the dictionary. If we try to, we will get a TypeError.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What happens if you try to access a key that doesn’t exist?

A

you get a KeyError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a dictonary?

A

A dictionary is an unordered set of key: value pairs.

It provides us with a way to map pieces of data to each other so that we can quickly find values that are associated with one another.

Example:
menu = {“avocado toast”: 6, “carrot juice”: 5, “blueberry muffin”: 2}
Notice that:

A dictionary begins and ends with curly braces { and }.
Each item consists of a key (“avocado toast”) and a value (6).
Each key: value pair is separated by a comma.
It’s considered good practice to insert a space () after each comma, but our code will still run without the space.

(Osea: Son como objetos en JS)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is dict comprehensions?

A

Let’s say we have two lists that we want to combine into a dictionary, like a list of students and a list of their heights, in inches:

names = [‘Jenny’, ‘Alexus’, ‘Sam’, ‘Grace’]
heights = [61, 70, 67, 64]
Python allows you to create a dictionary using a dict comprehension, with this syntax:

students = {key:value for key, value in zip(names, heights)}
#students is now {‘Jenny’: 61, ‘Alexus’: 70, ‘Sam’: 67, ‘Grace’: 64}
Remember that zip() combines two lists into an iterator of tuples with the list elements paired together. This dict comprehension:

Takes a pair from the iterator of tuples
Names the elements in the pair key (the one originally from the names list) and value (the one originally from the heights list)
Creates a key : value item in the students dictionary
Repeats steps 1-3 for the entire iterator of pairs
mira:

drinks = [“espresso”, “chai”, “decaf”, “drip”]
caffeine = [64, 40, 0, 120]

zipped_drinks=zip(drinks,caffeine)

drinks_to_caffeine={key:value for key, value in zipped_drinks}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What type can be the keys?

A

strings or numbers

17
Q

What type can be the values?

A

Values can be of any type. We can use a string, a number, a list, or even another dictionary as the value associated with a key!

18
Q

can dictionaries be empty?

A

yes.

We can create an empty dictionary like this:

empty_dict = {}