Dictionary

A dictionary is a list of associations composed by a unique key and corresponding structures. Dictionaries are mutable, like lists.

The key must be an immutable type, usually strings, but can also be tuples or numeric types. On the other hand the items of dictionaries can be either mutable or immutable. The Python dictionary provides no guarantee that the keys are ordered.

Syntax:

dictionary = {'a': a, 'b': b, ..., 'z': z}

Structure:

Example of a dictionary:

dic = {'name': 'Dabar', 'band': 'Honey'}

Acessing elements:

print (dic['name'])

Adding elements:

dic['key_1'] = '120'

Removing one elemento from a dictionary:

del dic['key_1']

Getting the items, keys and values:

items = dic.items()
keys = dic.keys()
values = dic.values()

Examples with dictionaries:


In [2]:
dic = {'name': 'Dabar', 'name': 'Dabar New', 'band': 'Honey'}
print(dic)
print(len(dic))


{'name': 'Dabar New', 'band': 'Honey'}
2

NOTE: Last key will override the previous one


In [4]:
print(dic.items())


dict_items([('name', 'Dabar New'), ('band', 'Honey')])

In [9]:
# Progs and their albums
progs = {'Yes': ['Close To The Edge', 'Fragile'],
    'Genesis': ['Foxtrot', 'The Nursery Crime'],
    'ELP': ['Brain Salad Surgery']}

# More progs
progs['King Crimson'] = ['Red', 'Discipline']

# items() returns a list of 
# tuples with key and value 
for singer, album  in progs.items():
    print(singer, ":=>", album)


Yes :=> ['Close To The Edge', 'Fragile']
Genesis :=> ['Foxtrot', 'The Nursery Crime']
ELP :=> ['Brain Salad Surgery']
King Crimson :=> ['Red', 'Discipline']

In [13]:
for albums in progs.values():
    print(albums)


['Close To The Edge', 'Fragile']
['Foxtrot', 'The Nursery Crime']
['Brain Salad Surgery']
['Red', 'Discipline']

In [14]:
for prog in progs:
    print(prog, "=>", progs[prog])


Yes => ['Close To The Edge', 'Fragile']
Genesis => ['Foxtrot', 'The Nursery Crime']
ELP => ['Brain Salad Surgery']
King Crimson => ['Red', 'Discipline']

In [15]:
# If there is 'ELP', removes
if 'ELP' in progs:
    del progs['ELP']
    
print(progs)


{'Yes': ['Close To The Edge', 'Fragile'], 'Genesis': ['Foxtrot', 'The Nursery Crime'], 'King Crimson': ['Red', 'Discipline']}

In [4]:
multid = {'school': 'DMS',
          'students_details': {
              1001: {
               "name": "Mayank",
                  "age": 41
              },
              1002: {
                "name" : "Vishal",
                "age": 42
              },
              1003: {
                  "name": "Rajeev Chaturvedi",
                  "age": 41
              }
          }
        }
print(multid)


{'school': 'DMS', 'students_details': {1001: {'name': 'Mayank', 'age': 41}, 1002: {'name': 'Vishal', 'age': 42}, 1003: {'name': 'Rajeev Chaturvedi', 'age': 41}}}

In [10]:
print(multid['students_details'][1001])
print(multid['students_details'][1002]['name'])


{'name': 'Mayank', 'age': 41}
Vishal

In [11]:
print(multid['students_details'][1004]['name'])


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-dccdb72595c6> in <module>()
----> 1 print(multid['students_details'][1004]['name'])

KeyError: 1004

In [18]:
multid = {'school': 'DMS',
          'students_details': {
              "students": 
                  [
                      "Mayank",
                      "Vishal",
                      "Rajeev"
                  ]
          }}
print(multid)


{'school': 'DMS', 'students_details': {'students': ['Mayank', 'Vishal', 'Rajeev']}}

In [8]:
dupli = {
    "meme" : "mjmj",
    "test" : "TESt value",
    "meme" : "wewe"
}

print(dupli)
for k in dupli:
    print(k)


{'test': 'TESt value', 'meme': 'wewe'}
test
meme

In [22]:
# Matrix in form of string
matrix = '''0 0 0 0 0 0 0 0 0 0 0 0
9 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 4 0 0
0 0 0 0 0 0 0 3 0 0 0 0
0 0 0 0 0 0 5 0 0 0 0 0
0 0 0 0 6 0 0 0 0 0 0 0'''

mat = {}

# split the matrix in lines
for row, line in enumerate(matrix.splitlines()):

    # Splits the line int cols
    for col, column in enumerate(line.split()):

        column = int(column)
        # Places the column in the result,
        # if it is differente from zero
        if column:
            mat[row, col] = column

print (mat)
# The counting starts with zero
print ('Complete matrix size:', (row + 1) * (col + 1))
print ('Sparse matrix size:', len(mat))


{(5, 4): 6, (3, 7): 3, (1, 0): 9, (4, 6): 5, (2, 9): 4}
Complete matrix size: 72
Sparse matrix size: 5

NOTE: One can create dictionary using the following methods as well


In [3]:
names = dict(mayank="johri", ashwini="johri", Rahul="Johri")
print(names)


{'mayank': 'johri', 'ashwini': 'johri', 'Rahul': 'Johri'}

In [29]:
names = dict([("mayank","johri"), ("ashwini", "johri"), ("Rahul","Johri")])
print(names)


{'ashwini': 'johri', 'mayank': 'johri', 'Rahul': 'Johri'}

Lets check below two examples and see what is happening


In [16]:
d = dict()
d[10.1] = "TEST"
d[10] = "test"  
d[10.5] = "really testing"
d[20] = "Testing completed"
print(d)


{10.1: 'TEST', 10.5: 'really testing', 20: 'Testing completed', 10: 'test'}

In [27]:
d = dict()
d[10.0] = "TEST"
d[10] = "test"  
d[10.5] = "really testing"
d[20] = "Testing completed"
print(d)


{10.0: 'test', 20: 'Testing completed', 10.5: 'really testing'}

NOTE: Dictionaries are implemented with a hash table and hash of 10.0 and 10 are same, thus 10.0 and 10 keys of dict are same and only one key/value pair is shown for them. Please check the url for details.


In [31]:
hash(10.0) == hash(10)


Out[31]:
True