12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Although the curly-braces literal form does see use, it is perhaps more common to seedictionaries built up in different ways. The following, for example, starts with anempty dictionary, and fills it out one key at a time. Unlike out-of-bounds assignmentsin lists, which are forbidden, an assignment to new dictionary key creates that key:>>> D = {}>>> D['name'] = 'Bob' # Create keys by assignment>>> D['job'] = 'dev'>>> D['age'] = 40>>> D{'age': 40, 'job': 'dev', 'name': 'Bob'}>>> print D['name']BobHere, we’re effectively using dictionary keys as field names in a record that describessomeone. In other applications, dictionaries can also be used to replace searchingoperations—indexing a dictionary by key is often the fastest way to code a search in<strong>Python</strong>.Nesting RevisitedIn the prior example, we used a dictionary to describe a hypothetical person, withthree keys. Suppose, though, that the information is more complex. Perhaps we needto record a first name and a last name, along with multiple job titles. This leads toanother application of <strong>Python</strong>’s object nesting in action. The following dictionary,coded all at once as a literal, captures more structured information:>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},'job': ['dev', 'mgr'],'age': 40.5}Here, we again have a three-key dictionary at the top (keys “name,” “job,” and“age”), but the values have become more complex: a nested dictionary for the nameto support multiple parts, and a nested list for the job to support multiple roles andfuture expansion. We can access the components of this structure much as we didfor our matrix earlier, but this time some of our indexes are dictionary keys, not listoffsets:>>> rec['name'] # 'Name' is a nested dictionary{'last': 'Smith', 'first': 'Bob'}>>> rec['name']['last'] # Index the nested dictionary'Smith'>>> rec['job'] # 'Job' is a nested list['dev', 'mgr']80 | Chapter 4: Introducing <strong>Python</strong> Object Types

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

Saved successfully!

Ooh no, something went wrong!