In [1]:
dict = {'key':'a', 'key1':'2', 'key2':'2.34'}
In [2]:
dict
Out[2]:
In [4]:
dict['key1']
Out[4]:
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]:
In [25]:
print('The cost of this item is: $' + car) # Alas after several attempts, this now prints out nicely.
In [32]:
out = 'some string $'
In [33]:
car = items['toy car']
In [34]:
out + car # See the difference.
In [35]:
print(out + str(car)) # Integers or float datatypes have to be cast to string.
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]:
In [45]:
d = dtypes['k3']
In [46]:
d
Out[46]:
In [49]:
list = d['key2']
In [50]:
list
Out[50]:
In [51]:
list[1]
Out[51]:
In [53]:
dtypes
Out[53]:
In [54]:
# The proper syntax to call nested values is as follows
dtypes['k3']['key2'][1]
Out[54]:
In [55]:
# Can then add methods for example:
dtypes['k3']['key2'][1].upper()
Out[55]:
In [56]:
nd = {'k1':100, 'k2':200}
In [57]:
nd
Out[57]:
In [59]:
nd.append('k3':300) # Bad, very bad.
In [60]:
nd['k3'] = 300
In [61]:
nd
Out[61]:
In [63]:
nd.keys()
Out[63]:
In [64]:
nd.items()
Out[64]:
In [67]:
nd.fromkeys('k2')
Out[67]:
In [69]:
nd.fromkeys('200')
Out[69]:
In [70]:
nd.values()
Out[70]:
In [71]:
nd.get('k3')
Out[71]:
In [ ]:
In [ ]: