Title: Dictionary Basics
Slug: dictionary_basics
Summary: Dictionary Basics
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Basics

  • Not sequences, but mappings. That is, stored by key, not relative position.
  • Dictionaries are mutable.

Build a dictionary via brackets


In [2]:
unef_org = {'name' : 'UNEF',
            'staff' : 32,
            'url' : 'http://unef.org'}

View the variable


In [3]:
unef_org


Out[3]:
{'name': 'UNEF', 'staff': 32, 'url': 'http://unef.org'}

Build a dict via keys


In [4]:
who_org = {}
who_org['name'] = 'WHO'
who_org['staff'] = '10'
who_org['url'] = 'http://who.org'

View the variable


In [5]:
who_org


Out[5]:
{'name': 'WHO', 'staff': '10', 'url': 'http://who.org'}

Nesting in dictionaries

Build a dictionary via brackets


In [6]:
unitas_org = {'name' : 'UNITAS',
              'staff' : 32,
              'url' : ['http://unitas.org', 'http://unitas.int']}

View the variable


In [7]:
unitas_org


Out[7]:
{'name': 'UNITAS',
 'staff': 32,
 'url': ['http://unitas.org', 'http://unitas.int']}

Index the nested list

Index the second item of the list nested in the url key.


In [8]:
unitas_org['url'][1]


Out[8]:
'http://unitas.int'