# Dictionary¶

Ha Khanh Nguyen (hknguyen)

## 1. What is a dictionary?¶

• Dictionary, dict, is a flexibly sized collection of key-value pairs, where key and value are Python objects.
• It is also known as hash map or associative array.

## 2. Elements of a Dictionary¶

### 2.1 Access, insert or set elements¶

• You can access, insert, or set elements using the same syntax as for accessing elements of a list or tuple:
• To check if a dict contains a key, we can use the in keyword:

### 2.2 Delete elements¶

• Use the del keyword to delete a key-value pair from a dict:

### 2.4 Merge dictionaries¶

• You can merge one dict into another using the update() method:

## 3. Creating Dictionary From Sequences¶

• Let's say you are given two lists a and b and you want to create a dictionary where the key are elements of a and the values are elements of b.
• Now, what happens if the two lists have different length?!
• Well, let's try that out in Jupyter Notebook!

### 3.1 The zip() function¶

• Note the zip() function that we used in the above code segment, this is a very useful function (especially with for loop).
• zip() “pairs” up the elements of a number of lists, tuples, or other sequences to create a list of tuples.
• zip() can take an arbitrary number of sequences, and the number of elements it produces is determined by the shortest sequence:

### 3.2 Unzip!¶

Given a "zipped" sequence, the zip() function can also be applied in a clevery way to "unzip" the sequence.

## Exercise¶

Let s be a string that contains a simple mathematical expression, e.g.,

s = '1.5 + 2.1'

s = '10.0-1.6'

s = '3.1*5.8'

s = '4.7 /7.2'

The expression will only have 2 operands and the operator will be one of the following: +, -, * and /.

Write a program that interpret the expression, then evaluate it and store the result in the result variable.

This lecture note is modified from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.