Checkpoint 10.1.1.
Write code that adds the key ‘two' with a value of ‘dos' to the dictionary eng2sp.
dict
creates a new dictionary with no items. Because dict
is the name of a built-in function, you should avoid using it as a variable name.{}
, represent an empty dictionary. To add items to the dictionary, you can use square brackets:>>> eng2sp['one'] = 'uno'
'one'
to the value “uno”. If we print the dictionary again, we see a key-value pair with a colon between the key and value:eng2sp = {'one':'uno'}
print(eng2sp)
{'one':'uno'}
eng2sp
, you might be surprised:>>> print(eng2sp['two'])
'dos'
'two'
always maps to the value “dos” so the order of the items doesn't matter.>>> print(eng2sp['four'])
KeyError: 'four'
len
function works on dictionaries; it returns the number of key-value pairs:>>> len(eng2sp)
3
in
operator works on dictionaries; it tells you whether something appears as a key in the dictionary (appearing as a value is not good enough).>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
pokemon_name_n_type = {'Squirtle': 'Water', 'Charmander': 'Fire', 'Bulbasaur' : 'Grass'}
print('Water' in pokemon_name_n_type)
values
, which returns the values as a list, and then use the in
operator:>>> vals = list(eng2sp.values())
>>> 'uno' in vals
True
in
operator uses different algorithms for lists and dictionaries. For lists, it uses a linear search algorithm. As the list gets longer, the search time gets longer in direct proportion to the length of the list. For dictionaries, Python uses an algorithm called a hash table that has a remarkable property: the in
operator takes about the same amount of time no matter how many items there are in a dictionary. I won't explain why hash functions are so magical, but you can read more about it at wikipedia.org/wiki/Hash_table 1 .fruits = {'apples': 1, 'bananas': 4, 'pears': 17, 'oranges': 14}
fruits['apples'] += fruits['bananas']
https://wikipedia.org/wiki/Hash_table