Dictionaries - Jupyter Notebook

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...

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.

• Dictionaries are Mutable


▪ note that key must be unique and immutable only values can be altered. This
means that a Python Tuple can be a key whereas a Python List can not
• They are unordered therefore indexing, slicing or striding are not possible

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

In [1]: 1 d1 = dict({"id": 1948, "name": "Washer", "size": 3}) # Created using di


2 d2 = dict(id=1948, name="Washer", size=3) # Created using keyword aregu
3 d3 = dict([("id", 1948), ("name", "Washer"), ("size", 3)]) # Created us
4 d4 = dict(zip(("id", "name", "size"), (1948, "Washer", 3))) # Created u
5 d5 = {"id": 1948, "name": "Washer", "size": 3} # Created using a dicti
6 print(d1)
7 print(d1["name"]) # referencing using key, It is not indexing

{'id': 1948, 'name': 'Washer', 'size': 3}


Washer

In [2]: 1 z= zip(("key1","key2"), ("value1", "value2")) # creates zip Object z


2 print(z, list(z))

<zip object at 0x000001C9508E0580> [('key1', 'value1'), ('key2', 'v


alue2')]

In [2]: 1 ## Some methods for dictionary


2 print(d1.items()) # returns list of dictioinary items
3 print(d1.keys()) # returns list of dictioinary keys
4 print(d1.values()) # returns list of dictioinary values
5 print(len(d1)) # returns the length of disctionary

dict_items([('id', 1948), ('name', 'Washer'), ('size', 3)])


dict_keys(['id', 'name', 'size'])
dict_values([1948, 'Washer', 3])
3

1 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...

Adding and deleting dictionary items

In [4]: 1 d1 = dict({"id": 1948, "name": "Washer", "size": 3, "class":'MSc'


2 print(d1)
3 d1["newkey"] ="newvalue1"
4 print(d1)
5 d1["newkey"] ="newvalue2" # keys are unique so newvalue2 will be assign
6 print(d1)
7 del(d1["name"]) # To delete key:values "name": 'washer'
8 print(d1)
9
10 d1.pop("newkey") #Items can also be removed (and returned) from the dic
11 print(d1)

{'id': 1948, 'name': 'Washer', 'size': 3, 'class': 'MSc'}


{'id': 1948, 'name': 'Washer', 'size': 3, 'class': 'MSc', 'newkey':
'newvalue1'}
{'id': 1948, 'name': 'Washer', 'size': 3, 'class': 'MSc', 'newkey':
'newvalue2'}
{'id': 1948, 'size': 3, 'class': 'MSc', 'newkey': 'newvalue2'}
{'id': 1948, 'size': 3, 'class': 'MSc'}

In [5]: 1 d1 = dict({"id": 1948, "tool": "Washer", "size": 3, "class":'MSc'


2 d2 = d1
3 d3 = dict({"id": 1950, "name": "Alpha", "class":'Centauri'})

In [ ]: 1

In [6]: 1 ## Set operations are allowed in dictionary view e.g.,


2 print(d1.keys()| d2.keys()) # Or operation
3 print(d1.items() - d2.items()) # set minus
4

{'class', 'tool', 'id', 'size'}


set()

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}

Example1: Create dictionary using a 3 tuple

In [3]: 1 tt= (("id", 1948), ("tool", "Washer"), ("size", 3), ("class",'MSc'

2 of 10 28/03/22, 13:27
Dictionaries - Jupyter Notebook http://localhost:8888/notebooks/Teaching/2021-22/Dictionarie...

In [6]: 1 d1 ={key:value for key,value in tt}


2 print(d1)
3
4 d2 ={key:value for key,value in tt if key =="tool"}
5 print(d2)

{'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'}


{'tool': 'Washer'}

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:

In [10]: 1 import os # importing os module


2 !pwd

/home/rkd/Teaching/2021-22

In [11]: 1 file_sizes = {name: os.path.getsize(name) for name in os.listdir(


2 # module’s os.listdir() function returns a list of the files and direc

In [12]: 1 file_sizes.items()

Out[12]: dict_items([('TOPICS-PTHON.docx', 13547), ('PMA21S03J-PYTHON-SYL.pd


f', 105759), ('Untitled.ipynb', 10813), ('Set_dictionaries.odt', 21
268), ('Set_dictionaries.pdf', 43974), ('TOPICS-PTHON.pdf', 18477),
('.ipynb_checkpoints', 4096), ('ct1-pyton.pdf', 80979), ('Dictionar
ies - Jupyter Notebook.pdf', 413641), ('Lab-bookMar21-2022.ipynb',
2637), ('Dictionaries.ipynb', 305969), ('material', 4096), ('ct1-py
ton.docx', 85593)])

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...

A default dictionary can be created by passing in a factory


function or user defined function/method
• A factory function is a function that, when called, returns an object of a
particular type.
▪ The factory function passed to a default dictionary is used to create default values
for missing keys
▪ Function to return a default values for keys that is not present

We can use python module collections

In [27]: 1 import collections


2 dict1 = collections.defaultdict(int)
3 print(dict1.values())

dict_values([])

In [28]: 1 dict1["key1"], dict1["key2"]

Out[28]: (0, 0)

In [29]: 1 print(dict1.values())
2 dict1

dict_values([0, 0])

Out[29]: defaultdict(int, {'key1': 0, 'key2': 0})

In [25]: 1 def key_value():


2 return "key is not present"
3
4 # Defining the dict
5 d2 = collections.defaultdict(key_value)
6 d2["a"] = 1
7 d2["b"] = 2
8 print(d2)

defaultdict(<function key_value at 0x7feab83b68b0>, {'a': 1, 'b':


2})

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.

In [30]: 1 # A Python program to demonstrate working of OrderedDict


2 from collections import OrderedDict
3
4 # Declare ordered dict
5 od = OrderedDict()
6 od['key1'] = 1
7 od['key2'] = 2
8 od['key3'] = 3
9 od['key4'] = 4
10
11 print("Before deleting:\n")
12 for key, value in od.items():
13 print(key, value)
14
15 print("\nAfter deleting:\n")
16 od.pop('key2')
17 for key, value in od.items():
18 print(key, value)
19
20 print("\nAfter re-inserting:\n")
21 od['key2'] = 2
22 for key, value in od.items():
23 print(key, value)
24

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

Iterators and Iterable Operations and

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.

• An iterator is an object that provides a __next__() method which returns each


successive item in turn, and raises a StopIteration exception when there
are no more items.

• 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

In [31]: 1 # Tuple is iterable


2 t_key = "k1", "k2", "k3"
3 print(t_key.__getitem__(slice(2)))
4 t_val = tuple([2,3,4])

('k1', 'k2')

In [33]: 1 # iterables can be converted into tuple or list


2 print(tuple(t_key), list(t_key))

('k1', 'k2', 'k3') ['k1', 'k2', 'k3']

Dictionaries are iterable


• The dict.items(), dict.keys(), and dict.values() methods all return dictionary views. A
dictionary view is effectively a read-only iterable object that appears to hold the
dictionary’s items or keys or values,
• We can also use membership function in to find if a particular key, value, or (key
value) is present in dictionary

In [35]: 1 # Creating Dictionary using tuple and iterating through


2 d= dict(zip(t_key, t_val))
3 d.keys()
4 for i in d.__iter__():
5 print(i, d.__getitem__(i))

k1 2
k2 3
k3 4

In [36]: 1 d1 = dict({"id": 1948, "tool": "Washer", "size": 3, "class":'MSc'


2 for item in d1.items():
3 print(item[0], item[1])
4 print(' ')
5
6 for key, value in d1.items():
7 print(key, value)
8 print(' ')

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

values in {'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'}


are 1948
values in {'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'}
are Washer
values in {'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'}
are 3
values in {'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'}
are MSc

In [37]: 1 # Find n! (factorial) for n<=10. We can do it using iterating over a li


2 n =5
3 lst = [ i for i in range(1, n+1)] # List comprehension
4 print(lst)
5 fact =1
6 ## iteration over list
7 for i in lst:
8 fact *=i
9 print('{}! is = {}'.format(n, fact))
10

[1, 2, 3, 4, 5]
5! is = 120

Common Iterable Operators and Functions

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

In [39]: 1 z[0]='G' # Changing object using z


2 print(x,z) # change occur at both

['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.

If we really do want a separate copy of the collection (or other


mutable object)

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)

In [40]: 1 songs = ["Because", "Boys", "Carol"]


2 beatles = songs[:]
3 beatles[2] = "Cayenne"
4 beatles, songs

Out[40]: (['Because', 'Boys', 'Cayenne'], ['Because', 'Boys', 'Carol'])

In [41]: 1 d1_copy= dict.copy(d1)


2 d1_copy["tool"]= "Gun" # Change made in the copy won't impact the initi
3 print(d1, d1_copy)

{'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'} {'id': 19


48, 'tool': 'Gun', 'size': 3, 'class': 'MSc'}

In [42]: 1 import copy


2 d2_copy= copy.copy(d1)
3 d2_copy["tool"]= "Driver" # Change made in the copy won't impact the in
4 print(d1, d2_copy)
5

{'id': 1948, 'tool': 'Washer', 'size': 3, 'class': 'MSc'} {'id': 19


48, 'tool': 'Driver', 'size': 3, 'class': 'MSc'}

Shallow v/s Deep Copying

All above methods are shallow copying that is, only


object references are copied and not the objects
themselves.
• For immutable datatype (like numbers, strings ) they are as good as deep copying
• For mutable data type like nested collections this means that the objects they refer to
are referred to both by the original collection and by the copied collection.

In [43]: 1 x = [53, 68, ["A", "B", "C"]]


2 y = x[:] # shalloow copy this means the reference to the nested list ["

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']])

In [ ]: 1 #### If we really need independent copies of arbitrarily nested collect

In [45]: 1 import copy


2 x = [53, 68, ["A", "B", "C"]]
3 y = copy.deepcopy(x)
4 y[1] = 40
5 x[2][0] = 'Q'
6 x, y

Out[45]: ([53, 68, ['Q', 'B', 'C']], [53, 40, ['A', 'B', 'C']])

In [46]: 1 id(x[2][0]), id(y[2][0])

Out[46]: (140646228064496, 140646229171696)

In [ ]: 1

10 of 10 28/03/22, 13:27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy