You are on page 1of 9

9/22/2020 Dictionary - Jupyter Notebook

Dictionary
A dictionary in Python is a collection of items accessed by a specific key rather than by index.

Imagine a dictionary in the real world... when you need to look up the meaning of a word, you try to find the
meaning using the word itself and not the possible index of the word.
Python dictionaries work with the same concept.

A dictionary is a collection which is unordered, changeable and


indexed.

In Python dictionaries are written with curly brackets, and they


have keys and values.

Syntax
{key:values , key:values , key:values}

a = {'apple': 'fruit', 'beetroot': 'vegetable', 'cake': 'dessert'}

Creating an empty Dictionary


When you don’t know what key-value pairs go in your Python dictionary, you can just create an empty Python
dict, and add pairs later.

In [1]:

d = {}
type(d)

Out[1]:

dict

In [2]:

d = dict()
type(d)

Out[2]:

dict

Adding elements

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 1/9


9/22/2020 Dictionary - Jupyter Notebook

In [5]:

square = {1:1,2:4,3:9,4:16,5:25}

In [6]:

# Add new pair 6:36


square[6]=36
square

Out[6]:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

In [7]:

square[10]=100
square

Out[7]:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 10: 100}

In [17]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}

date = '22-6-2020'
# date day
month[int(date.split('-')[1])]

Out[17]:

'Jun'

Accessing a value
Python dictionary is unordered. So to get a value from it, you need to put its key
in square brackets.

In [18]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
month[6]

Out[18]:

'Jun'

In [19]:

month[2]

Out[19]:

'Feb'

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 2/9


9/22/2020 Dictionary - Jupyter Notebook

Updating the Value of an Existing Key


If the key already exists in the Python dictionary, you can reassign its value using square brackets

In [20]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
month[3]='March'
month

Out[20]:

{1: 'Jan',
2: 'Feb',
3: 'March',
4: 'Apr',
5: 'May',
6: 'Jun',
7: 'July',
8: 'Aug',
9: 'Sep'}

Adding a new key


However, if the key doesn’t already exist in the dictionary, then it adds a new one.

In [21]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
month[10]='Oct'
month

Out[21]:

{1: 'Jan',
2: 'Feb',
3: 'Mar',
4: 'Apr',
5: 'May',
6: 'Jun',
7: 'July',
8: 'Aug',
9: 'Sep',
10: 'Oct'}

Delete Python Dictionary


Deleting a single key-value pair
To delete just one key-value pair, use the keyword ‘del’ with the key of the pair to delete.

e.g.
del dict1[1]

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 3/9


9/22/2020 Dictionary - Jupyter Notebook

Deleting an entire Python dictionary


To delete the whole Python dict, simply use its name after the keyword ‘del’

e.g.
del dict

In [22]:

# Deleting a single key-value pair


dict1={1:1,2:4,3:9,4:16,5:25,6:36}
del dict1[3]
print(dict1)

{1: 1, 2: 4, 4: 16, 5: 25, 6: 36}

In [23]:

# Deleting a single key-value pair


dict1={1:1,2:4,3:9,4:16,5:25,6:36}
del dict1
print(dict1)

---------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-dbaf89294259> in <module>
2 dict1={1:1,2:4,3:9,4:16,5:25,6:36}
3 del dict1
----> 4 print(dict1)

NameError: name 'dict1' is not defined

In [24]:

stu = {"Name":"Rahul" , "Age":24 , "Branch":"ECE","Section":"B"}


stu["Age"]=20
print(stu)

{'Name': 'Rahul', 'Age': 20, 'Branch': 'ECE', 'Section': 'B'}

In [25]:

dict1 = {"Name":"Rahul" ,("marks1","Marks2"):[45,56]}


print(dict1)

{'Name': 'Rahul', ('marks1', 'Marks2'): [45, 56]}

Rules for keys and Values


Key --> must be a immutable data type ( int, string , tuple )

Values can be mutable or immutable

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 4/9


9/22/2020 Dictionary - Jupyter Notebook

In [26]:

# Example
dict = {1:'abc','name':'ram',(12,34):45}
dict

Out[26]:

{1: 'abc', 'name': 'ram', (12, 34): 45}

In [27]:

# Example of mutable key . It gives us error

dict = {'name':'ram',[12,34]:56}
dict

---------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-32cdf011fa55> in <module>
1 # Example of mutable key . It gives us error
2
----> 3 dict = {'name':'ram',[12,34]:56}
4 dict

TypeError: unhashable type: 'list'

Generic funtion like ( len(),max(),min(),sum())


In [28]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
len(month)

Out[28]:

In [31]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
max(month)

Out[31]:

In [32]:

month = {1:'Jan',2:'Feb',3:'Mar',4:'Apr',5:'May',6:'Jun',7:'July',8:'Aug',9:'Sep'}
min(month)

Out[32]:

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 5/9


9/22/2020 Dictionary - Jupyter Notebook

In [33]:

sum(month)

Out[33]:

45

Methods with Description


1. dict.clear()
Removes all elements of dictionary dict.

In [1]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
print("Before clear",dict1)
dict1.clear()
print("After Clear",dict1)

Before clear {'Name': 'Ram', 'Age': 34, 'City': 'Ghaziabad', 'Contact': [971
1001100, 9911001100]}
After Clear {}

2. dict.copy()
Returns a shallow copy of dictionary dict.

In [2]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
dict2=dict1.copy()
print(dict2)

{'Name': 'Ram', 'Age': 34, 'City': 'Ghaziabad', 'Contact': [9711001100, 9911


001100]}

3. dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.

In [10]:

key=["Name","Age","City"]
value='Empty'
d = dict.fromkeys(key,value)
d

Out[10]:

{'Name': 'Empty', 'Age': 'Empty', 'City': 'Empty'}

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 6/9


9/22/2020 Dictionary - Jupyter Notebook

4. dict.get(key1, default=None)
For key key1, returns value or default if key not in dictionary.

In [12]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
dict1['Marks']

---------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-12-d191728ff7ac> in <module>
1 dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[971100110
0,9911001100]}
----> 2 dict1['Marks']

KeyError: 'Marks'

In [16]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
print(dict1.get('Age','Keys Not available'))

34

5. dict.items()
Returns a list of dict's (key, value) tuple pairs.

In [17]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
print(dict1.items())

dict_items([('Name', 'Ram'), ('Age', 34), ('City', 'Ghaziabad'), ('Contact',


[9711001100, 9911001100])])

6. dict.keys()
Returns list of dictionary dict's keys.

In [18]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
print(dict1.keys())

dict_keys(['Name', 'Age', 'City', 'Contact'])

7. dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict.

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 7/9


9/22/2020 Dictionary - Jupyter Notebook

In [21]:

dict1={1:1,2:4,3:9}
dict2 = {1:'ram',4:16}
dict1.update(dict2)
dict1

Out[21]:

{1: 'ram', 2: 4, 3: 9, 4: 16}

8. dict.values()
Returns list of dictionary dict's values.

In [19]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
print(dict1.values())

dict_values(['Ram', 34, 'Ghaziabad', [9711001100, 9911001100]])

In [32]:

# Loop over dict


dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
for key in dict1:
print(dict1[key])

Ram
34
Ghaziabad
[9711001100, 9911001100]

In [35]:

dict1={"Name":"Ram","Age":34,"City":"Ghaziabad","Contact":[9711001100,9911001100]}
for i in dict1.items():
print(i[1])

Ram
34
Ghaziabad
[9711001100, 9911001100]

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 8/9


9/22/2020 Dictionary - Jupyter Notebook

In [36]:

# WAP to create a dict such that it have 1 to 10 natural number as a key


#and square of that number will be as value.
# {1:1,2:4,3:9,4:16........,10:100}
d = {}
for i in range(1,11):
d[i]=i*i
d

Out[36]:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

In [43]:

# Concept of login page


login_det = {101:{'name':'ram','pass':'abc'},102:{'name':'sohan','pass':'abes'},103:{'name'

n = input("Enter your name")


p = input("Enter your passward")
for key in login_det:
if n ==login_det[key]['name'] and p == login_det[key]['pass']:
print("Valid user")
break

else:
print("Not a valid user")

Enter your namemohan


Enter your passwardabes
Not a valid user

Function and Operator

len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

localhost:8888/notebooks/Desktop/2020-21/EC Python/EC-A/content/Dictionary.ipynb 9/9

You might also like