Docsity

Python Dictionaries: Mapping Keys to Values, Assignments of Linguistics

Toggle sidebar
bg1
LIN 392, Spring 2009
Working with Corpora
Katrin Erk
Python:
Dictionaries
Dictionaries in Python
Python lists can store an ordered sequence of items, for
example a list of words. But when you want to map one type
of items to another, you need a Python dictionary.
Example cases where you could use a Python dictionary:
!!Mapping English words to their German translations
!!Mapping each word to its count in Wilkie Collins’ “The
woman in white”
!!Mapping each preposition to the verbs with which it occurs
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Python Dictionaries: Mapping Keys to Values and more Assignments Linguistics in PDF only on Docsity!

LIN 392, Spring 2009

Working with Corpora

Katrin Erk

Python:

Dictionaries

Dictionaries in Python

Python lists can store an ordered sequence of items, for

example a list of words. But when you want to map one type

of items to another, you need a Python dictionary.

Example cases where you could use a Python dictionary:

!! Mapping English words to their German translations

!! Mapping each word to its count in Wilkie Collins’ “The

woman in white”

!! Mapping each preposition to the verbs with which it occurs

Mapping English words to German

translations with a Python dictionary

>>> mydict = {}

>>> mydict[“dog”] = “Hund”

>>> mydict[“cat”] = “Katze”

>>> mydict[“rhinoceros”] = “Nashorn”

>>> mydict[“dog”]

Hund

Initialization of a dictionary: mydict = {}

Note: curly brackets! Used only for

dictionaries in Python.

A dictionary maps a key (e.g. “dog”) to a

value (e.g. “Hund”)

Comparing Python dictionaries

and Python lists

Initializing to an empty data structure:

mylist = [] # empty list: straight brackets

mydict = {} # empty dictionary: curly brackets

Initializing to a nonempty data structure:

# initializing a list:straight brackets

mylist = [“dog”, “cat”, “rhinoceros”]

# initializing a dictionary: curly brackets, key-colon-value

mydict = {"dog":"Hund", "cat":"Katze”, \

“rhinoceros":"Nashorn"}

What can be a dictionary key?

Strings can be dictionary keys: mydict = {"dog":"Hund", "rhinoceros":"Nashorn"} Integers can be dictionary keys. The following dictionary (somewhat redundantly) maps prime numbers to their rank, e.g. 2 is the first prime number. prime_nums = {2:1, 3:2, 5:3, 7:4, 11:5} Floating point numbers can be dictionary keys as well: >>> mydict = {3.1415 : "pi", 2.71828 : "e" } >>> mydict[3.1415] 'pi’ Lists cannot be dictionary keys – more on this later: >>> mydict = {[1,2] : "wont_work"} Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list'

What can be a dictionary value?

Any data type can be a dictionary value. Here is again our first

example, where the dictionary values were strings:

mydict = {“dog”:”Hund”, “rhinoceros”:”Nashorn”}

Here is an example where dictionary values are lists:

>>> preps_and_verbs = {}

>>> preps_and_verbs['to'] = ['see', 'go', 'belong']

>>> preps_and_verbs

{'to': ['see', 'go', 'belong']}

Even a dictionary can be a dictionary value.

Counting words

paragraph from the Onion, March 04

paragraph = ”””While dieters are accustomed to exercises of will, a new English translation of Germany's most popular diet book takes the concept to a new philosophical level. The Nietzschean diet, which commands its adherents to eat superhuman amounts of whatever they most fear, is developing a strong following in America.””” counts = { } for word in paragraph.split(): if not(counts.has_key(word)): counts[word] = 0 counts[ word ] = counts[ word ] + 1 for word in counts.keys(): print word, counts[word] counts.has_key(word) is a conditional that is true if the dictionary ‘counts’ has a key that is the same as the contents of the variable ‘word’. counts.keys() yields the list of keys of the dictionary ‘counts’.

An idiom:

Accumulating things in a dictionary

This is a variant of the accumulator idiom you know. To count

occurrences of each word, we initialize its count to zero

when we encounter it for the first time. We know we

encounter it for the first time because there is no dictionary

key for them yet.

for word in paragraph.split():

if not(counts.has_key(word)): counts[word] = 0

# Once the accumulator is initialized, we use it as

# before:

counts[ word ] = counts[ word ] + 1

for-loops and Python dictionaries

Iterating over all keys in the dictionary:

mydict = { “dog” : “Hund”, “rhinoceros” : “Nashorn”}

for english in mydict.keys():

print “I got the following English animal:”, english

Iterating over all values in the dictionary:

for german in mydict.values():

print “I got the following German animal:”, german

Iterating over all key/value pairs in the dictionary:

for english, german in mydict.items():
print “The German translation of ”, english, “is”, german
Remember:You do not know what order the items
will be in.

Iterating over two things at once? We get back to this in a minute.

Dictionary keys

What can be a dictionary key? As we saw earlier: strings,

integers, floating point numbers, but not lists.

>>> mydict[ [1,2] ] = "one two” Traceback (most recent call last): File "", line 1, in? TypeError: list objects are unhashable

Here is the rule: Any non-mutable data type can be a key

!! Not lists: they are mutable

!! Strings, integers, and floats are non-mutable

!! Tuples are like lists, except that they are not mutable

Tuples: like lists, but immutable

>>> mytuple = (1, 2, 3)
>>> type(mytuple)
>>> mytuple[ 1 ]
>>> mytuple[ 1 ] = 1
Traceback (most recent call last):
File "", line 1, in?
TypeError: object does not support item assignment

Use round brackets for initializing a

tuple: mytuple = (1,2,3). Use straight

brackets to access tuple items at a given

index.

Taking a list or tuple apart

If you know how many members a list or tuple has, you can assign

them to different variables in a single step:

>>> mytuple = (1,2,3)

>>> var1, var2, var3 = mytuple

>>> var

But you should be sure you know how many members the list or

tuple has:

>>> var1, var2 = mytuple

Traceback (most recent call last):

File "", line 1, in

ValueError: too many values to unpack

Another very useful method of

dictionaries: get

You can access the dictionary value for a given key using straight brackets: >>> mydict = { “dog” : “Hund”, “rhinoceros” : “Nashorn”} >>> mydict[‘dog’] ‘Hund’ You can also use get(): >>> mydict.get(‘dog’) ‘Hund’ The advantage of get() is that you can give a default: >>> mydict['butterfly'] Traceback (most recent call last): File "", line 1, in KeyError: 'butterfly' >>> mydict.get('butterfly', 'Schmetterling') 'Schmetterling’

Another very useful method of

dictionaries: get

mydict.get(key, default)

!! If mydict has a key named key: return mydict[key]
!! else: return default

Here is an example where get() is indeed very useful:

counts = { }

for word in paragraph.split():

counts[ word ] = counts.get(word, 0) + 1

for word in counts.keys():

print word, counts[word]