Calvin (Deutschbein)
W11Mon: 04 Nov
Python dictionaries use squiggly brackets
{}
to enclose their contents
Can create an empty dictionary by providing no key-value pairs:
d = {}
Or via "dict()" (like list(), int(), etc)
d = dict()
skewlz = {'Willamette': "Bearcat", "Carolina": "Tarheel", "Chicago:": "Phoenix"}
>>> skewlz = {'Willamette': "Bearcat", "Carolina": "Tarheel", "Chicago:": "Phoenix"}
>>> skewlz["Carolina"]
'Tarheel'
>>> skewlz["Willamette"]
'Bearcat'
>>> d = {"Fav Prof":"Calvin", "Fav Prof":"Anyone else"}
>>> d
{'Fav Prof': 'Anyone else'}
>>> d = {"Fav Prof":"Calvin", "Fav Prof":"Anyone else"}
>>> d
{'Fav Prof': 'Anyone else'}
[]
You instead use the key directly to select corresponding values:
>>> movie = {"Franchise" : "Alien", "Entry": "Romulus"}
>>> movie["Entry"]
'Romulus'
>>> movie["anything bad"]
Traceback (most recent call last):
File "<stdin>", line 1, in
KeyError: 'anything bad'
'ei' in word and 'cei' not in word
>>> movie = {"Franchise" : "Alien", "Entry": "Romulus"}
>>> "anything bad" in movie
False
>>> "Year" in movie
True
>>> "Franchise" in movie
True
>>> "Alien" in movie
False
>>> "Franchise" in movie
True
>>> movie["Franchise"]
'Alien'
>>> movie = {"Franchise" : "Alien", "Entry": "Romulus"}
>>> movie["Franchise"]
'Alien'
>>> movie["Franchise"] = "AVP"
>>> movie["Franchise"]
'AVP'
for key in movie:
value = movie[key]
print("The", key, "of the movie is", value)
The Franchise of the movie is Alien
The Entry of the movie is Romulus
for key, value in movie.items():
print("The", key, "of the movie is", value)
The Franchise of the movie is Alien
The Entry of the movie is Romulus
>>> for key, value in movie.items():
... if value == "Alien":
... print(key)
...
Franchise
Method call | Description |
---|---|
len(d) |
Returns the number of key-value pairs in the dictionary |
d.get(key, value) |
Returns the value associated with the given key in the dictionary. If the key is not found, returns None |
d.pop(key) |
Removes the key-value pair corresponding to key and returns the associated value. Will raise an error if the key is not found. |
d.clear() |
Removes all key-value pairs from the dictionary, leaving it empty. |
d.items() |
Returns an iterable object that cycles through the successive tuples consisting of a key-value pair. Iterables are weird - either use this within a for loop, or convert it to a list with list() |
console = {
'name': 'XBox',
'vers': 360,
}