The dictionary data type


In [1]:
myCat = {'size': 'fat', 'color':'gray', 'disposition':'loud'}

In [2]:
myCat['size']


Out[2]:
'fat'

In [3]:
'My cat has ' + myCat['color'] + ' fur.'


Out[3]:
'My cat has gray fur.'

In [4]:
spam = {12345: 'Luggage Combination', 42: 'The Answer'}

Dictionaries vs. Lists


In [5]:
spam = ['cats', 'dogs', 'moose']

In [6]:
bacon = ['dogs', 'moose', 'cats']

In [7]:
spam == bacon


Out[7]:
False

In [8]:
eggs = {'name': 'Zophies', 'species': 'cat', 'age': 8}

In [9]:
ham = {'species': 'cat', 'age': 8, 'name': 'Zophies'}

In [10]:
eggs == ham


Out[10]:
True

In [11]:
spam['color']


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-4ab2633f52b0> in <module>()
----> 1 spam['color']

TypeError: list indices must be integers or slices, not str

The keys(), values(), and items() Methods


In [12]:
spam = {'color': 'red', 'age': 42}

In [13]:
for v in spam.values():
    print(v)


red
42

In [14]:
for k in spam.keys():
    print(k)


color
age

In [15]:
for i in spam.items():
    print(i)


('color', 'red')
('age', 42)

In [16]:
spam.keys()


Out[16]:
dict_keys(['color', 'age'])

In [17]:
list(spam.keys())


Out[17]:
['color', 'age']

In [18]:
for k, v in spam.items():
    print('Key: ' + k + ', Value: ' + str(v))


Key: color, Value: red
Key: age, Value: 42

Checking Whether a Key or Value Exists in a Dictionary


In [19]:
spam = {'name': 'Zophie', 'age': 7}

In [20]:
'name' in spam.keys()


Out[20]:
True

In [21]:
'Zophie' in spam.values()


Out[21]:
True

In [22]:
'color' in spam


Out[22]:
False

In [23]:
'color' not in spam.keys()


Out[23]:
True

In [25]:
'color' in spam.keys()


Out[25]:
False

The get() Method


In [26]:
picnicItems = {'apples': 5, 'cups': 2}

In [27]:
'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'


Out[27]:
'I am bringing 2 cups.'

In [28]:
'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'


Out[28]:
'I am bringing 0 eggs.'

In [29]:
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-29-b435afff13bf> in <module>()
----> 1 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'

KeyError: 'eggs'

The setdefault() Method


In [30]:
spam = {'name': 'Pooka', 'age': 5}

In [31]:
if 'color' not in spam:
    spam['color'] = 'black'

In [32]:
spam


Out[32]:
{'age': 5, 'color': 'black', 'name': 'Pooka'}

In [36]:
spam = {'name': 'Pooka', 'age': 5}

In [34]:
spam.setdefault('color', 'black')


Out[34]:
'black'

In [35]:
spam


Out[35]:
{'age': 5, 'color': 'black', 'name': 'Pooka'}

In [ ]: