Dictionaries

7
Click to edit Master subtitle style 10/28/09 Dictionaries Emad Nawfal

description

Dictionaries. Emad Nawfal. A minimal dictionary. english2arabic = {'man': 'rajul', 'country': 'balad', 'peace': 'salam', 'terror': 'irhab', 'child': 'tifl'}. Dictionaries have pairs of items. - PowerPoint PPT Presentation

Transcript of Dictionaries

Page 1: Dictionaries

Click to edit Master subtitle style

10/28/09

Dictionaries

Emad Nawfal

Page 2: Dictionaries

10/28/09

A minimal dictionary

english2arabic = {'man': 'rajul',

'country': 'balad',

'peace': 'salam',

'terror': 'irhab',

'child': 'tifl'}

Page 3: Dictionaries

10/28/09

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.

Page 4: Dictionaries

10/28/09

Dictionaries support the in operator (tests for keys, not values)

Dictionaries support iterationThe .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

Page 5: Dictionaries

10/28/09

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.

Page 6: Dictionaries

10/28/09

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

Page 7: Dictionaries

10/28/09

Advanced Topics

Dictionaries of dictionaries Dictionaries of lists Lists of dictionaries Use a database if possible. Things get

ugly quickly.