Dictionaries - Jupyter Notebook
Dictionaries - Jupyter Notebook
Dictionaries - Jupyter Notebook
Dictionaries
A dict is used to store data values like a map . Precsely it is an unordered collection of zero
or more key–value pairs whose keys are object references that refer to hashable objects,
and whose values are object references referring to objects of any type.
Dictionary creation
• The dict data type can be called as a function, dict()—with no arguments it returns an
empty dictionary, and with a mapping argument it returns a dictionary based on the
argument
• Dictionaries can also be created using braces—empty braces, {},
• format {key1:value1, key2:value2,...}
Examples
1 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
In [ ]: 1
Dictionary Comprehension
• A dictionary comprehension is an expression and a loop with an optional
condition enclosed in braces. Syntaxes are
• {keyexpression: valueexpression for key, value in iterable}
• {keyexpression: valueexpression for key, value in iterable if
condition}
2 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
Example 2:
• dictionary comprehension to create a dictionary where each key is the name of a file in
the current directory and each value is the size of the file in bytes:
/home/rkd/Teaching/2021-22
In [12]: 1 file_sizes.items()
Default Dictionaries
• If we use a nonexistent (“missing”) key when accessing a dictionary, a KeyError is
raised and it might become a problem.
• To overcome this Python introduces another dictionary like container known as
Defaultdict which is present inside the collections module. For exmple
In [11]: 1 d1["sigma"]
-------------------------------------------------------------------
--------
KeyError Traceback (most recent ca
ll last)
~\AppData\Local\Temp/ipykernel_11352/3939401923.py in <module>
----> 1 d1["sigma"]
KeyError: 'sigma'
3 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
dict_values([])
Out[28]: (0, 0)
In [29]: 1 print(dict1.values())
2 dict1
dict_values([0, 0])
In [26]: 1 print(d2["a"])
2 print(d2["b"])
3 print(d2["c"])
1
2
key is not present
In [ ]: 1 print(d2)
Ordered Dictionaries
• OrderedDict preserves the order in which the keys are inserted.
4 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
• A regular dict doesn’t track the insertion order and iterating it gives the values in an
arbitrary order. By contrast, the order the items are inserted is remembered by
OrderedDict.
Before deleting:
key1 1
key2 2
key3 3
key4 4
After deleting:
key1 1
key3 3
key4 4
After re-inserting:
key1 1
key3 3
key4 4
key2 2
5 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
Functions
• An iterable data type is one that can return each of its items one at a time.
• Any object that has an __iter__() method, or any sequence (i.e., an object
that has a __getitem__() method taking integer arguments starting from 0) is
an iterable and can provide an iterator.
• The order in which items are returned depends on the underlying iterable. In
the case of lists and tuples, items are normally returned in sequential order
starting from the first item (index position 0), but some iterators return the items
in an arbitrary order—for example, dictionary
('k1', 'k2')
k1 2
k2 3
k3 4
6 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
9
10 for value in d1.values():
11 print('values in {} are {}'.format(d1, value))
12
id 1948
tool Washer
size 3
class MSc
id 1948
tool Washer
size 3
class MSc
[1, 2, 3, 4, 5]
5! is = 120
7 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
Copying Collections
• Since Python uses object references, when we use the assignment operator ( =).
The syntax is simply objectReference = value . Note that The = operator
is not the same as the variable assignment operator in some other languages.
The = operator binds an object reference to an object in memory. The = operator
binds an object reference to an object in memory. Lets look at the following
example
In [38]: 1 x = [1,2,3,4] # python creates a list object with the and an 'object re
2 y = ['a', 'b', 'c']
3 z = x # It creates a new object reference called z and sets it to refe
4 print(x,z)# x and z object reference to the same object i.e.list [1,2,3
5 print('Memory address of object reference by x and z are', hex(id
[1, 2, 3, 4] [1, 2, 3, 4]
Memory address of object reference by x and z are 0x7feab8436dc0 0x
7feab8436dc0
['G', 2, 3, 4] ['G', 2, 3, 4]
It is clear that = oprator creates a new object reference z, and both object references
x and z refer to the same list—no copying has taken place. So any change made
through either object is visible to other.
8 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
e.g.,
• For sequences, when we take a slice. slice is always an independent copy of the items
copied.
• For dictionaries and sets, copying can be achieved using dict.copy() and set.copy(). In
addition, the copy module provides the copy.copy() function that returns a copy of the
object it is given.
• Another way to copy the built-in collec tion types is to use the type as a function with
the collection to be copied as its argument e.g.,
▪ copy_of_dict_d = dict(d)
▪ copy_of_list_L = list(L)
▪ copy_of_set_s = set(s)
9 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...
3 # This means that both x and y have as their third item an object refer
4 # so any changes to the nested list are seen by both x and y. Think str
5 print(id(x[2][0]), id(y[2][0]))
6 x, y
140646229171696 140646229171696
Out[43]: ([53, 68, ['A', 'B', 'C']], [53, 68, ['A', 'B', 'C']])
In [44]: 1 y[1] = 40
2 x[2][0] = 'Q'
3 x, y
4
Out[44]: ([53, 68, ['Q', 'B', 'C']], [53, 40, ['Q', 'B', 'C']])
Out[45]: ([53, 68, ['Q', 'B', 'C']], [53, 40, ['A', 'B', 'C']])
In [ ]: 1
10 of 10 28/03/22, 13:27