0% found this document useful (0 votes)
528 views9 pages

Dictionary in Python

The document discusses dictionaries in Python. It defines dictionaries as unordered sets of key-value pairs that are represented using curly braces {}. Dictionaries allow for fast lookup of values based on keys. Keys must be immutable types like strings or integers, while values can be mutable types. Dictionaries do not maintain order and do not support indexing or slicing. Elements can be accessed and modified using square brackets and keys. The document also discusses creating, updating, and manipulating dictionaries using various functions and methods.

Uploaded by

Nargis Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
528 views9 pages

Dictionary in Python

The document discusses dictionaries in Python. It defines dictionaries as unordered sets of key-value pairs that are represented using curly braces {}. Dictionaries allow for fast lookup of values based on keys. Keys must be immutable types like strings or integers, while values can be mutable types. Dictionaries do not maintain order and do not support indexing or slicing. Elements can be accessed and modified using square brackets and keys. The document also discusses creating, updating, and manipulating dictionaries using various functions and methods.

Uploaded by

Nargis Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

DICTIONARY IN PYTHON

 Dictionary is an unordered set of key-value pairs.


 Dictionary represents by {} braces.
 Dictionaries are also known as associative arrays or mappings or
hashes.
 In Dictionary keys are immutable types (string, tuple or int) and
values are mutable types.
 Dictionary doesn’t maintain order due to hash code, so one cannot
access element as per specific order.
 Indexing and Slicing are not possible in Dictionary.
 To access element, can use square [] brackets with keys.

# empty dictionary
samp_dict = {}
print(samp_dict)

# dictionary with integer keys


samp_dict = {1: 'Cricket', 2: 'Basketball'}
print(samp_dict)

# dictionary with string keys


samp_dict = {'eid': 101, 'ename': 'Amit', 'edsg': 'Programmer'}
print(samp_dict)

# dictionary with mixed keys


samp_dict = {'name': 'Amit', 1: [22, 50, 60], ('Phone','Mobile'): 557856}
print(samp_dict)

# using dict()
samp_dict = dict({1:'Cricket', 2:'Tennis'})
print(samp_dict)
# from sequence having each item as a pair
samp_dict = dict([(1,'Computer Science'), (2,'Informatics Practices')])
print(samp_dict)

 Creation of Dictionary:
1. Adding key: value pairs to an empty dictionary:
a. Student = {}
b. Student = dict()
c. Add key:value pairs, one at a time as follows:
Student[‘rno’] = 10
2. Using dict() functions:
a. Specify key:value pairs as keyword argument
employee = dict(name = 'Amit', dsg = 'Analyst', salary = 50000 )
print(employee)
{'name': 'Amit', 'dsg': 'Analyst', 'salary': 50000}
b. Using comma-separated key:value pairs:
employee = dict({'name':'Amit', 'dsg':'Analyst', 'salary':50000} )
print(employee)
{'name': 'Amit', 'dsg': 'Analyst', 'salary': 50000}
c. Specify keys separately and corresponding values separately in
parenthesis (as tuples)
employee = dict(zip(('name','dsg','salary'),('Amit','Analyst',
50000)))
print(employee)
{'name': 'Amit', 'dsg': 'Analyst', 'salary': 50000}
d. Specify key:value pairs separately in form of sequences:
employee = dict([['name','Amit'],['salary',50000],['dsg','Analyst']])
print(employee)
employee = dict([('name','Amit'),('salary',50000),('dsg','Analyst')])
print(employee)
employee = dict((('name','Amit'),('salary',50000),('dsg','Analyst')))
print(employee)
 Update/Modifying Existing elements:
In Dictionaries, the updation and addition of elements are similar in
syntax:
employee = {'name': 'Amit', 'salary': 50000, 'dsg': 'Analyst'}
employee['name'] = 'Sachin'
print(employee)
{'name': 'Sachin', 'salary': 50000, 'dsg': 'Analyst'}
Note: If key doesn’t exist new entry will be added

 Dictionary Functions and methods:


fromkeys(): is used to create a new dictionary from a sequence
containing all the keys and a common value, which will be assigned to all
the keys:
emp = dict.fromkeys([10, 20, 30], 5000)
print(emp)
{10: 5000, 20: 5000, 30: 5000}

emp = dict.fromkeys([10, 20, 30], (80, 20))


print(emp)
{10: (80, 20), 20: (80, 20), 30: (80, 20)}
 Extend/Update Dictionary with new key: value pairs:
o Dict.setdefault() : it insert a new key:value pair if key doesn’t
exist, if key exist, it returns current value of the key
d = {1:'Amit', 2:'Sachin', 3:'Ram'}
d.setdefault(4,'Kunnal') # will return kunnal
print(d)
{1: 'Amit', 2: 'Sachin', 3: 'Ram', 4: 'Kunnal'}

o Dict.update(): This method merges key: value pairs from the new
dictionary into the original one, new items will be added and the
old one override if any items already exist with same keys.
d = {1: 'Amit', 2: 'Sachin', 3: 'Ram', 4: 'Kunnal'}
d2 = {2:'Tarun', 5:'Ajay'}
print(d)
{1: 'Amit', 2: 'Tarun', 3: 'Ram', 4: 'Kunnal', 5: 'Ajay'}

Python Dictionary Comprehension


Dictionary comprehension is an elegant and concise way to create a
new dictionary from an iterable in Python.
Dictionary comprehension consists of an expression pair (key: value)
followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair
of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to


squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Theoretical Questions and Answers
1. Why can’t we apply slicing and concatenation on dictionaries?
2. How do you add key: value pairs to an existing Dictionary?
3. How can we remove key: value pairs from a Dictionary?
4. What type of objects can be used as keys in Dictionary?
5. Can you modify the keys in the dictionary?
6. Is Dictionary Mutable? Why?
7. How are dictionaries being different from Lists?
8. If we add a new key : value pair in the dictionary, Is it the size of the
dictionary will grow or an error occurs.
9. How is clear() function different from del Statement?
10. Why is a dictionary termed as an unordered collection of
objects?
11. Merge the following two dictionaries into one:

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}


dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

12. Below are the two lists convert it into the Dictionary:

keys = ['Ten', 'Twenty', 'Thirty']


values = [10, 20, 30]

13. Access the value of key ‘history’ from the below dictionary:
MyDict = {
"class":{
"student":{
"name":"Mike",
"marks":{
"physics":70,
"history":80
}
}
}
}
14. Check if a value 200 exists in a dictionary
sampleDict = {'a': 100, 'b': 200, 'c': 300}
15. Rename the key ‘city’ to ‘location’ in the following dictionary:

sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
16. Which of the following will result in an error for a given
valid dictionary D?
a. D + 3
b. D * 3
c. D + {3 : '3'}
d. D.update({3: '3'})
e. D.update({{'3':3}})

Output Based Question on Dictionary


1. Dictionaries are _____________ set of elements:
a. Sorted
b. Ordered
c. Unordered
d. Random

2. Dictionaries are also called:


a. Mappings
b. Hashes
c. Associative arrays
d. All of these

3. Dictionaries are ________ data types of Python.


a. Mutable
b. Immutable
c. Simple
d. All of these

4. Which of the following functions will return the key, value pairs of a
dictionary?
a. Keys()
b. Values()
c. Items()
d. All of these

5. Which of the following can be used to delete items from a


dictionary?
a. del statement
b. pop()
c. popitem()
d. All of these

6. Which of the following will raise an error if the given dictionary is


empty?
a. del statement
b. pop()
c. popitem()
d. All of these

7. Which of the following is correct with respect to above Python


code?
d = {'a':3,'b':7}
a. A dictionary d is created.
b. A and b are the keys of dictionary d.
c. 3 and 7 are the values of dictionary d.
d. All of these

8. Predict the output:


d = {'spring':'autumn', 'autumn':'fall', 'fall':'spring'}
a. autumn
b. fall
c. spring
d. Error

9. Which of the following will delete key_value pair for key =’tiger’ in
the dictionary?
d = {'lion':'wild', 'tiger':'wild', 'cat':'domestic', 'dog': 'domestic'}
a. d['tiger']
b. d['tiger'].delete()
c. delete(d.['tiger'])
d. del(d.['tiger'])

10. Which of following Python codes will give the same output if
dict = {'diary': 1,'book':3, 'novel':5}
a. dict.pop('book')
b. del dict['book']
c. dict.update({'diary':1,'novel':5})

11. What will be the output of the following Python code?


d1 = {'a':10, 'b':2, 'c':3}
str1 = ''
for i in d1:
str1 = str1 + str(d1[i]) + ' '
str2 = str1[:-1]
print(str2[::-1])
a. 3, 2
b. 3, 2, 10
c. 3, 2, 01
d. Error
12. What does the following block of code do?

You might also like