= {
greetings 'en': 'Hello',
'fr': 'Bonjour',
'de': 'Hallo'
}
Dictionaries
Unit 05
A new data type
Similarly to a list, a dictionary, or dict, is a data type that contains collections of data (both are containers). However, while a list contains ordered sequences of data, which are indexed1 by their integer location, a dictionary provides a mapping between keys and corresponding values. Let’s look at an example of a language dictionary implemented in a python dictionary:
In this example, each key associates a language ('en', 'fr', 'de'
) with the corresponding greeting ('Hello', 'Bonjour', 'Hallo'
). The languages represent the keys, and the greeting formulas represent the values. The dictionary is constructed with curly brackets {}
and the key–value pairs are separated with a colon :
. Analogously to lists, different key–value pairs are separated with a comma.
Dictionaries are indexed by their keys, so to access the greeting formula in French, we would call
'fr'] greetings[
'Bonjour'
To add or edit key–value pairs (dicts are mutable) and to remove a key–value pair, you can do
'by'] = 'Habediehre'
greetings[del greetings['en']
You can check whether a key exists in a dictionary by
if 'by' in greetings:
print(greetings['by'])
Habediehre
You can iterate over dictionary keys by
for language in greetings:
print(greetings[language])
Bonjour
Hallo
Habediehre
JSON and pandas
Python dictionaries can often be very useful, but if you still wonder why you should know yet another data type, consider these two reasons:
- The popular file format JSON and python dictionaries have many syntactical similarities. If you ever have to work with JSON files, this is where you should start.
- In the next step, you will learn about a very powerful data analysis package for python, called pandas. Unlike NumPy, which specialized on numerics and is built around n-dimensional arrays, pandas excels in manipulating and analyzing data frames, or in other words tabular data you all know from spreadsheet software. pandas’ data frames are also indexed by keys, so they “feel” similar to python dictionaries.
Learning checklist
Footnotes
read: accessed for now↩︎