Dictionary


Dictionary is like a list, but the indexes can be anything we like, which are known as key.
Dictionary consists of key value pairs. The key value pair are stored in dictionary as - {'key': 'value'} and these key value pairs are separated by comma and enclosed in curly brackets.

In [1]:
superhero = {'name': 'Deadpool', 'universe':'marvel', 'suit-color':'red'}
In [2]:
superhero['universe']
Out[2]:
'marvel'



In list, order matters, but in dictionary order doesn't matter.
i.e Dictionary is unordered

In [3]:
[1, 2, 3] == [2, 3, 1]
Out[3]:
False
In [4]:
{1, 2, 3} == {2, 3, 1}
Out[4]:
True
In [5]:
'name' in superhero
Out[5]:
True
In [6]:
'Deadpool' in superhero
Out[6]:
False



variables equated to dictionaries are merely references to the original dictionary stored in memory. Just like in lists. For more info, see list and strings notebook.



Methods on dictionary are keys(), values(), items()

In [7]:
superhero.keys()
Out[7]:
dict_keys(['name', 'universe', 'suit-color'])

lets convert that to list

In [8]:
list(superhero.keys())
Out[8]:
['name', 'universe', 'suit-color']
In [9]:
list(superhero.values())
Out[9]:
['Deadpool', 'marvel', 'red']
In [10]:
list(superhero.items())
Out[10]:
[('name', 'Deadpool'), ('universe', 'marvel'), ('suit-color', 'red')]
In [11]:
superhero
Out[11]:
{'name': 'Deadpool', 'suit-color': 'red', 'universe': 'marvel'}



for loop on dictionary

In [12]:
for This_is_random_variable in superhero.keys():
    print(This_is_random_variable)
name
universe
suit-color
In [13]:
for This_is_random_variable in superhero.values():
    print(This_is_random_variable)
Deadpool
marvel
red
In [14]:
for This_is_random_variable in superhero.items():
    print(This_is_random_variable)
('name', 'Deadpool')
('universe', 'marvel')
('suit-color', 'red')

The values returned above are 3 tuples. Tuples are same things as lists except they are immutable and uses round brackets


In [15]:
for k,v in superhero.items():
    print(k, v)
name Deadpool
universe marvel
suit-color red
In [16]:
'Deadpool' in superhero.values()
Out[16]:
True



get() method

get( , ) method is used to get value of specific key in the dictionary. The key whose value we want to get in the first argument, and if that key doesnt't exist, it returns the second argument value

In [17]:
superhero.get('suit-color', "This key doesn't exist")
Out[17]:
'red'
In [18]:
superhero.get('power', "This key doesn't exist")
Out[18]:
"This key doesn't exist"




setdefault() method

In [19]:
superhero
Out[19]:
{'name': 'Deadpool', 'suit-color': 'red', 'universe': 'marvel'}
In [20]:
if 'power' not in superhero:
    superhero['power'] = 'healing'
In [21]:
superhero
Out[21]:
{'name': 'Deadpool',
 'power': 'healing',
 'suit-color': 'red',
 'universe': 'marvel'}
In [22]:
del superhero['power'] #deletes the power key and its value
In [23]:
superhero
Out[23]:
{'name': 'Deadpool', 'suit-color': 'red', 'universe': 'marvel'}



Above code can be done using setdefault() using one line. It defines new key value pair in the dictionary if that key doesn't exist yet. If that key is already there, then it does nothing.
It is used to make sure a certain key is present in the dictionary

In [24]:
superhero
Out[24]:
{'name': 'Deadpool', 'suit-color': 'red', 'universe': 'marvel'}
In [25]:
superhero.setdefault('power', 'healing')
Out[25]:
'healing'
In [26]:
superhero
Out[26]:
{'name': 'Deadpool',
 'power': 'healing',
 'suit-color': 'red',
 'universe': 'marvel'}

Now if we do that again with another value, it won't do anything

In [27]:
superhero.setdefault('power', 'funny')
Out[27]:
'healing'
In [28]:
superhero
Out[28]:
{'name': 'Deadpool',
 'power': 'healing',
 'suit-color': 'red',
 'universe': 'marvel'}




I will now write a code that tells the number of times each letter appeared in the string

In [29]:
someString = 'And she looked at the sky and wondered is this all there is?'
count = {}


for char_variable in someString:     #iterates over each character in the string same as in list 
    count.setdefault(char_variable, '0')       #adds the value of 0 to the character when a new character is encountered 
    count[char_variable] = count[char_variable] + 1


count
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-29-82aee5e4e648> in <module>()
      5 for char_variable in someString:     #iterates over each character in the string same as in list
      6     count.setdefault(char_variable, '0')       #adds the value of 0 to the character when a new character is encountered
----> 7     count[char_variable] = count[char_variable] + 1
      8
      9

TypeError: must be str, not int

Oops! An error. I will just leave it here so in future I won't do that again. The error is that I enclosed the 0 in quotation marks, making it string, and we can't add an integer to the string.
using int(count[char_variable]) would have also worked.


In [30]:
someString = 'And she looked at the sky and wondered is this all there is?'
count = {}


for char_variable in someString:     #iterates over each character in the string same as in list 
    count.setdefault(char_variable, 0)       #adds the value of 0 to the character when a new character is encountered 
    count[char_variable] = count[char_variable] + 1


count
Out[30]:
{' ': 12,
 '?': 1,
 'A': 1,
 'a': 3,
 'd': 5,
 'e': 7,
 'h': 4,
 'i': 3,
 'k': 2,
 'l': 3,
 'n': 3,
 'o': 3,
 'r': 2,
 's': 5,
 't': 4,
 'w': 1,
 'y': 1}






New bug free code that counts upper and lower alphabets as same by converting them all to upper letters.

In [31]:
someString = 'And she looked at the sky and wondered is this all there is?'
count = {}


for char_variable in someString.upper():     #iterates over each character in the string same as in list 
    count.setdefault(char_variable, 0)       #adds the value of 0 to the character when a new character is encountered 
    count[char_variable] = count[char_variable] + 1


count
Out[31]:
{' ': 12,
 '?': 1,
 'A': 4,
 'D': 5,
 'E': 7,
 'H': 4,
 'I': 3,
 'K': 2,
 'L': 3,
 'N': 3,
 'O': 3,
 'R': 2,
 'S': 5,
 'T': 4,
 'W': 1,
 'Y': 1}



pprint module

pprint or 'pretty print' can be used to get pretty output of a list or dictionary.

In [32]:
import pprint

pprint.pprint(count)
{' ': 12,
 '?': 1,
 'A': 4,
 'D': 5,
 'E': 7,
 'H': 4,
 'I': 3,
 'K': 2,
 'L': 3,
 'N': 3,
 'O': 3,
 'R': 2,
 'S': 5,
 'T': 4,
 'W': 1,
 'Y': 1}

The pformat function in pprint module is used to get pretty output in the string format.

In [33]:
import pprint

pprint.pformat(count)
Out[33]:
"{' ': 12,\n '?': 1,\n 'A': 4,\n 'D': 5,\n 'E': 7,\n 'H': 4,\n 'I': 3,\n 'K': 2,\n 'L': 3,\n 'N': 3,\n 'O': 3,\n 'R': 2,\n 'S': 5,\n 'T': 4,\n 'W': 1,\n 'Y': 1}"



type() function

type() funtion tells us about the data type of the argument

In [34]:
type(count)
Out[34]:
dict
In [35]:
type('')
Out[35]:
str
In [36]:
type(42)
Out[36]:
int
In [37]:
type(True)
Out[37]:
bool
In [38]:
type(4 == 4)
Out[38]:
bool
In [39]:
type(print())

Out[39]:
NoneType
In [40]:
somelist = [1,2,4]
In [41]:
type(somelist)
Out[41]:
list