12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11DictionariesAdictionaryislikealist,butmoregeneral. Inalist,theindiceshavetobeintegers;inadictionarythey can be(almost)any type.You can think of a dictionary as a mapping between a set of indices (which are called keys) and aset of values. Each key maps to a value. The association of a key and a value is called a key-valuepair or sometimes an item.As an example, we’ll build a dictionary that maps from English to Spanish words, so the keys andthevalues areall strings.The function dict creates a new dictionary with no items. Because dict is the name of a built-infunction, you should avoid using itas avariable name.>>> eng2sp = dict()>>> print eng2sp{}The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you canusesquare brackets:>>> eng2sp['one'] = 'uno'Thislinecreatesanitemthatmapsfromthekey’one’tothevalue'uno'. Ifweprintthedictionaryagain, weseeakey-value pair withacolon between the key and value:>>> print eng2sp{'one': 'uno'}This output format is also an input format. For example, you can create a new dictionary with threeitems:>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}But ifyou printeng2sp,you might besurprised:>>> print eng2sp{'one': 'uno', 'three': 'tres', 'two': 'dos'}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!