Chapter 9: Dictionaries Flashcards
difference between dictionary and list
dictionary is more general - maps between a set of indicies (keys) and a set of values
key
set of indicies that maps to a value
association of a key and a value…
called a key-value pair, or an item
turn eng2ger (english to german dictionary) into a dictionary
eng2ger=dict()
braket type of dictionary
{ } - curly brackets.
create item mapping key ‘one’ to value ‘eins’
eng2ger[‘one’]=’eins’
print(eng2ger)
{‘one’: ‘eins’}
add more
eng2ger[‘x’]=’y’, will just add new ones
creating dict with multiple items at start
eng2ger={‘three’: ‘drei’, ‘four’: ‘vier’} - output can be used to create new one
show value of a key
print(eng2ger[‘one’]) returns eins
find number of items
len(eng2ger), returns no. of items
‘in’ operator can be used to tell us if a…
key is in the dictionary, but not a value. eg
‘one’ in eng2ger #returns True, but ‘eins’ returns False
to see if a value is in dictionary…
use the ‘values’ method to return a list, then use the ‘in’ operator. x=list(eng2ger.values())
‘eins’ in x #returns true
what does c mean, as in “for c in str
character
dictionary to tally characters in a string, ie give frequency of each
word='brontosaurus' d=dict() for c in word: if c not in d: < d[c]=1 < else: < d[c]=d[c]+1 <
print(d)