Get startedGet started for free

Dictionaries

Dictionaries are similar to named vectors and lists in R in that they provide a name (or key) for you to access values. In Python, dictionaries are created using a pair of curly brackets, { }, and passed in key-value pairs. Keys and values are separated with a colon. For example to create a dictionary with the key, 'a' and a value of 1, you write:

d = {'a': 1}

Multiple key-value pairs are separated by a comma. To access a value by the key, you can use square brackets (just like subsetting values from a list), but instead of passing in an index, you pass in the key:

d = {'a': 1, 'b': 2}
print(d['a'])

1

person_list is printed in the IPython shell and is available in your workspace.

This exercise is part of the course

Python for R Users

View Course

Exercise instructions

  • Create a dictionary form of person_list which is printed in the shell. Use the keys, fname, lname, sex, employed, and twitter_followers.
  • Extract and print the first and last names (specified by the keys fname and lname) from person_dict.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Create a dictionary form of the employee information list
person_dict = {
    'fname': ____,
    'lname': ____,
    'sex': ____,
    'employed': ____,
    'twitter_followers': ____
}

# Get the first and last names from the dict
print(____)
print(____)
Edit and Run Code