Dictionaries in python are Mappings (or associations). Means they store values in key and value associations (pair).
Example: 'color' : 'Blue'
Here color is the key and Blue is the value. notice that key and value are seperated by :. These key value pairs are enclosed in { and }.
You can consider them as associative arrays in some languages.
In [1]:
myDict = {'color':'blue', 'taste':'sweet'}
In [2]:
myDict
Out[2]:
We can access the elements of a dictionary using index, but here we do not use number indexes. Instead we use the key as index to access the value.
In [3]:
myDict['taste']
Out[3]:
The values in a dictionary can be any python object. It can be a integer, floating point, string, List or even another dictionary.
In [4]:
myDict = {'first':123,'second':3.1415,'third':'hello world!'}
In [5]:
myDict
Out[5]:
In [6]:
myDict['second']
Out[6]:
In [7]:
myDict['third']
Out[7]:
You can use any function on the value in a dictionary.
In [8]:
myDict['third'].upper()
Out[8]:
In [9]:
# Accessing a single character
myDict['third'][0]
Out[9]:
In [10]:
# Slicing the string
myDict['third'][0:5]
Out[10]:
In [11]:
# Reversing the string
myDict['third'][::-1]
Out[11]:
In [12]:
myDict['second']*2
Out[12]:
All these are temporary operations, they dont change the dictionary values permanently.
In [13]:
myDict
Out[13]:
We can create a dictionary by assignment also. As with lists, dictionary are also not of fixed size. You can add any number of values to a dictionary.
In [14]:
d = {}
Now we have created a dictionary which doesn't has any values. An empty dictionary.
In [15]:
d
Out[15]:
We can insert a value directly into the dictionary by using its key.
In [16]:
d['element'] = 'Oxygen'
In [17]:
d['weight'] = 15.999
In [18]:
d
Out[18]:
We can put a list as a value in a dictionary.
In [19]:
d['list'] = [1,2,3]
In [20]:
d
Out[20]:
In [21]:
d['list'][1]
Out[21]:
Like lists and any other objects, dictionaries can also be nested.
In [22]:
nestDict = {'d1': {'element':'Oxygen', 'weight':15.999}, 'd2':{'element': 'Hydrogen', 'weight':1}}
In [23]:
nestDict
Out[23]:
In [24]:
nestDict['d1']['element']
Out[24]:
In [25]:
nestDict['d2']['weight']
Out[25]:
In [28]:
# Keys in a dictionary.
myDict.keys()
Out[28]:
In [29]:
# Values in a dictionary.
myDict.values()
Out[29]:
In [36]:
myDict.items()
Out[36]:
Python offers many functions on dictionaries like clear(), copy(), fromkeys(), get(), pop(), popitem(), setdefault(), update().
You can also use len() function on a dictionary.
In [38]:
len(myDict)
Out[38]: