Dictionaries Flashcards

1
Q

dictionary basics:

overwrite a dictionary is the same as creating a new dictionary item.

delete an item from a dictionary

determine the number of key-value pairs in a dictionary

A

fruitbasket[“mango”] = 1

del fruitbasket[“banana”]

len( fruitbasket )

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

dictionary methods:

dict.copy( )
keys( ), values( ), items( )

get( )
strawberry = fruitbasket.get( “strawberry”, 0 )
output:
number of strawberries in the basket: 0

A

shallow copy: dict.copy( )
deep copy: use deepcopy( ) function from copy module

The method keys() provides an iterator that lists all the keys of a dictionary. The method values() provides an iterator that lists all the values of a dictionary. The method items() provides an iterator that lists all the key-value pairs of a dictionary as tuples.

You cannot apply the sort() method to the list casting, i.e., keylist = list( fruitbasket.key() ).sort() does not work. You must first create the list, then sort it. Neither can you write for key in keylist.sort(), as the sort() method has no return value.

The get() method can be used to get a value from a dictionary even when you do not know if the key for which you seek the value exists. You call the get() method with the key you are looking for, and it will return the corresponding value when the key exists in the dictionary, or the special value None when the key does not exist in the dictionary. If you want to return a specific value instead of None if the key does not exist, you can add that value as a second argument to the method.

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

The code block below contains a list of words. Build a dictionary that contains all these words as keys, and how often they occur as values. Then print the words with their quantities.

A
# Word counts.
wordlist = ["apple","durian","banana","durian","apple","cherry","cherry","mango"]
def word_dictionary_list(word_list):
    f_basket = {}
    for fruit in wordlist:
        f_basket[fruit] = wordlist.count(fruit)
return f_basket

print(word_dictionary_list(wordlist))

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