Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 89

Dictionaries

Оглавление

Another very useful data type to learn is the dictionary. A dictionary (commonly referred to as a dict) is a mapping that stores data in key-value pairs, rather than simply a list or sequence of values. A mapping is a collection that allows you to look up information associated with key values (Zelle, 2010). Dictionary keys locate values within a dictionary and can be any immutable type, most often being strings or numbers. However, you should not use floating point numbers as dictionary keys because computers store them as approximations (Python Software Foundation, 2019, “Mapping Types—dict”). Known in other languages as associative arrays or hash tables, this enables the programmer to store multiple related data values in one structure and reference them by their specified key values. Consider a physical dictionary. The “key” is the word you would like to reference, and the “value” would be the definition for which you are searching. Understanding how dictionaries work will help you when we work with data from the Web using JavaScript Object Notation (JSON; in Chapter 7) and when we transform data into required formats for data visualization (in Chapter 9).

One way to create a dictionary object is to use an assignment statement in which the right-hand side has key-value pairs specified in curly braces “( ).” We specify the key-value pairs within the curly braces using the format key:value and separate the pairs by commas. To illustrate this, the Python code in Figure 3.17 creates a simple dictionary based on some overall counts of survey information. Lines 2 to 4 of the code in Figure 3.17 identify the keys in the dictionary to be “survey_count,” “2014_takers,” and “2016_takers” and the corresponding values for the keys are 1000, 43, and 52, respectively. It can be very useful to store data in a structure where all the data elements are related and to look up a value using a string key that makes sense in that context. The output from running this code is shown in Figure 3.18.

Description

Figure 3.17 GSS Dictionary Example

Description

Figure 3.18 Output from GSS Dictionary Example

Introduction to Python Programming for Business and Social Science Applications

Подняться наверх