π Dictionary
Good to know
βοΈ Dictionaries store keyβvalue pairs. Keys must be unique, values can repeat.
Creating a Dictionary
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
8: "August" # keys can also be numbers
}Manipulating Dictionary
Accessing Values
βοΈ .get() is safer: it avoids errors when the key is missing.
monthConversions["Feb"] # β 'February'
monthConversions.get("Feb") # β 'February'
monthConversions.get("GG") # β None
monthConversions.get("GG", "Not available")
# β 'Not available'Useful Dictionary Methods
shortcuts = {
"DE": "Germany",
"CH": "Switzerland",
"P": "Portugal"
}
shortcuts.keys() # β all keys
shortcuts.values() # β all values
shortcuts.items() # β key/value pairs
shortcuts.update({"E": "Spain"}) # add new pair
shortcuts.update({"CH": "Schweiz"}) # overwrite existing value
shortcuts.pop("P") # remove key 'P'
shortcuts.clear() # empty the dictionaryLooping Through a Dictionary
Find here how to loop through a dictionary: Looping Through a Dictionary
**Using kwargs (Arguments Stored as a Dictionary)
kwargs collects named arguments into a dictionary.