70 likes | 237 Views
Dictionaries. Emad Nawfal. A minimal dictionary. english2arabic = {'man': 'rajul', 'country': 'balad', 'peace': 'salam', 'terror': 'irhab', 'child': 'tifl'}. Dictionaries have pairs of items.
E N D
Dictionaries Emad Nawfal
A minimal dictionary english2arabic = {'man': 'rajul', 'country': 'balad', 'peace': 'salam', 'terror': 'irhab', 'child': 'tifl'}
Dictionaries have pairs of items. • Each item has a key and a value. • Dictionaries are indexed by keys, not by digits indicating position as in lists • The key has to be an immutable type: what are immutable types? • The values can be anything.
Dictionaries support the in operator (tests for keys, not values) • Dictionaries support iteration • The .values() method gets us all the values. • The .keys() method gets us all the keys. • The .items() method gets us all the items. • Dict1.py as an example
Building dictionaries programmatically • It is very tedious to build dictionaries by hand. • You can build dictionaries programmatically easily in two steps: • Initialize a dictionary • Update the dictionary keys.
Counting words with dictionaries • Question: How do you count word frequencies in a text? • Can we use: listname.count(x)? • Dictionaries: buildDict.py • Default dictionaries: countWords.py
Advanced Topics • Dictionaries of dictionaries • Dictionaries of lists • Lists of dictionaries • Use a database if possible. Things get ugly quickly.