In [1]:
dict = {'key':'a', 'key1':'2', 'key2':'2.34'}

In [2]:
dict


Out[2]:
{'key': 'a', 'key1': '2', 'key2': '2.34'}

In [4]:
dict['key1']


Out[4]:
'2'

In [5]:
#good exmaple of dictionary usecase would be items in a store.
items = {'apples':1.76, 'bananas':1.00, 'toy car':2.99}

In [23]:
car = str(items['toy car']) #to call an integer as a string this must be cast inside parenthises.

In [24]:
car


Out[24]:
'2.99'

In [25]:
print('The cost of this item is: $' + car) # Alas after several attempts, this now prints out nicely.


The cost of this item is: $2.99

In [32]:
out = 'some string $'

In [33]:
car = items['toy car']

In [34]:
out + car # See the difference.


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-34-3962787f3896> in <module>()
----> 1 out + car # See the difference.

TypeError: must be str, not float

In [35]:
print(out + str(car)) # Integers or float datatypes have to be cast to string.


some string $2.99

In [40]:
dtypes = {'k1':23, 'k2':[1, 2, 3], 'k3':{'key':'value1', 'key1':23.4, 'key2':['a', 'b', 'c']}}
#Examples of nesting and multiple datatypes including nesting lists within dictionaries and dictionaries inside dictionaries.

In [44]:
dtypes['k3']


Out[44]:
{'key': 'value1', 'key1': 23.4, 'key2': ['a', 'b', 'c']}

In [45]:
d = dtypes['k3']

In [46]:
d


Out[46]:
{'key': 'value1', 'key1': 23.4, 'key2': ['a', 'b', 'c']}

In [49]:
list = d['key2']

In [50]:
list


Out[50]:
['a', 'b', 'c']

In [51]:
list[1]


Out[51]:
'b'

In [53]:
dtypes


Out[53]:
{'k1': 23,
 'k2': [1, 2, 3],
 'k3': {'key': 'value1', 'key1': 23.4, 'key2': ['a', 'b', 'c']}}

In [54]:
# The proper syntax to call nested values is as follows
dtypes['k3']['key2'][1]


Out[54]:
'b'

In [55]:
# Can then add methods for example:
dtypes['k3']['key2'][1].upper()


Out[55]:
'B'

In [56]:
nd = {'k1':100, 'k2':200}

In [57]:
nd


Out[57]:
{'k1': 100, 'k2': 200}

In [59]:
nd.append('k3':300) # Bad, very bad.


  File "<ipython-input-59-8870947e74f8>", line 1
    nd.append('k3':300) # Bad, very bad.
                  ^
SyntaxError: invalid syntax

In [60]:
nd['k3'] = 300

In [61]:
nd


Out[61]:
{'k1': 100, 'k2': 200, 'k3': 300}

In [63]:
nd.keys()


Out[63]:
dict_keys(['k1', 'k2', 'k3'])

In [64]:
nd.items()


Out[64]:
dict_items([('k1', 100), ('k2', 200), ('k3', 300)])

In [67]:
nd.fromkeys('k2')


Out[67]:
{'2': None, 'k': None}

In [69]:
nd.fromkeys('200')


Out[69]:
{'0': None, '2': None}

In [70]:
nd.values()


Out[70]:
dict_values([100, 200, 300])

In [71]:
nd.get('k3')


Out[71]:
300

In [ ]:


In [ ]: