Dictionaries in Python:
=================
Basic
Types in Python :
==================
a=10 #int
b="hello" #str
c=2.5 #float
e=bytearray() #bytearray
f=(1,2,3) #tuple
g=[1,2,3] #list
h={1,2,3} #set
i={} #dict
j=b"sample" #bytes
k=None #empty
=====================
a=10 #int
b="hello" #str
c=2.5 #float
e=bytearray() #bytearray
f=(1,2,3) #tuple
g=[1,2,3] #list
h={1,2,3} #set
i={} #dict
j=b"sample" #bytes
k=None #empty
=====================
What
are Dictionaries?
Dictionary is a Python built-in data type that is used to store collections of unordered key-value pairs.
Dictionary is a Python built-in data type that is used to store collections of unordered key-value pairs.
Why
Dictionaries?
Dictionaries offer the association of keys to their corresponding values. Each key refers to one (and only one) value in the dictionary. This not only facilitates storing and processing of data, but also enriches the whole process by enabling the user to store data in pairs. This greatly enhances searching and indexing operations.
Dictionaries offer the association of keys to their corresponding values. Each key refers to one (and only one) value in the dictionary. This not only facilitates storing and processing of data, but also enriches the whole process by enabling the user to store data in pairs. This greatly enhances searching and indexing operations.
What
are the Features of Dictionaries?
- Dictionaries
are collections of key-value pairs.
- Dictionaries
are unordered: unlike lists that have values stored in a certain order
based on the array index, dictionaries don’t maintain one order for its
data items.
- Data items are
accessed by keys, not by
indexes.
Syntax
for Initializing Dictionaries
A dictionary name is an identifier (just like variable names, list names, and function names). Dictionaries are assigned values using the normal assignment operators ‘=’.
A dictionary name is an identifier (just like variable names, list names, and function names). Dictionaries are assigned values using the normal assignment operators ‘=’.
D1 = {1
: ‘IT’, 2 : ‘Sales’, 3 : ‘Finance’, 4 : ‘HR’ }
From
the above statement, we can notice that:
- Dictionaries
are delimited by curly braces.
- A key comes
before its corresponding value.
- Keys and
values are separated by colons ‘:’
- Like lists,
pairs are separated from each other’s by commas ‘,’
·
It is an container that
contains data, enclosed within curly braces.
·
The pair i.e., key and
value is known as item.
·
The key passed in the
item must be unique.
·
The key and the value is
separated by a colon(:). This pair is known as item. Items are separated from
each other by a comma(,).
·
Different items are
enclosed within a curly brace and this forms Dictionary.
·
Dictionaries are
optimized to retrieve values when the key is known.
Example:
data={100:'Manish' ,101:'Vijay' ,102:'Rahul'}
print (data)
Output:
{100: 'Manish', 101: 'Vijay', 102: 'Rahul'}
·
Dictionary is mutable i.e., value can be updated.
·
Key must be unique and
immutable. Value is accessed by key.
·
Value can be updated
while key cannot be changed.
·
Dictionary is known as Associative array since the Key works
as Index and they are decided by the user.
Example:
plant={}
plant[1]='Ravi'
plant[2]='Manoj'
plant['name']='Hari'
plant[4]='Om'
print (plant[2])
print (plant['name'])
print (plant[1])
print (plant)
Output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 4: 'Om', 'name':
'Hari'}
How
to create a dictionary?
# empty dictionary
my_dict
= {}
# dictionary with integer keys
my_dict
= {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict
= {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict
= dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict
= dict([(1,'apple'), (2,'ball')])
Accessing Values
Since
Index is not defined, a Dictionaries value can be accessed by their keys.
Syntax:
[key]
Example:
data1={'Id':100,
'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101,
'Name':'Ramesh', 'Profession':'Trainer'}
print
"Id of 1st employer is",data1['Id']
print
"Id of 2nd employer is",data2['Id']
print
"Name of 1st employer:",data1['Name']
print
"Profession of 2nd employer:",data2['Profession']
Output:
Id of
1st employer is 100
Id of
2nd employer is 101
Name
of 1st employer is Suresh
Profession
of 2nd employer is Trainer
Updation
The
item i.e., key-value pair can be updated. Updating means new item can be added.
The values can be modified.
Example:
data1={'Id':100,
'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101,
'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print
(data1)
print
(data2)
Output:
{'Salary':
15000, 'Profession': 'Manager','Id': 100, 'Name': 'Suresh'}
{'Salary':
20000, 'Profession': 'Trainer', 'Id': 101, 'Name': 'Ramesh'}
Deletion
del
statement is used for performing deletion operation.
An
item can be deleted from a dictionary using the key.
Syntax:
del [key]
Example:
data={100:'Ram',
101:'Suraj', 102:'Alok'}
del
data[102]
print
data
del
data
print
data #will show an error since
dictionary is deleted.
Output:
{100:
'Ram', 101: 'Suraj'}
Traceback
(most recent call last):
File "C:/Python27/dict.py", line 5,
in
print data
NameError:
name 'data' is not defined
Functions and Methods
Python
Dictionary supports the following Functions:
Functions:
1) len(dictionary)
Example:
data={100:'Ram',
101:'Suraj', 102:'Alok'}
print
(data)
print
(len(data))
Output:
{100: 'Ram', 101: 'Suraj', 102:
'Alok'}
3
2) str(): produces a
printable string representation
of a dictionary.
Syntax
Following is the syntax
for str() method −
str(dict)
Example:
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7,
'Class': 'First'}
print ("Equivalent String :
%s" % str (dict))
Output:
Equivalent String : {'Name': 'Manni',
'Age': 7, 'Class': 'First'}
3) type(variable):Returns the type of
the passed variable. If passed variable is dictionary, then it would return a
dictionary type.
Syntax
Following is the syntax for type() method
−
type(dict)
Example:
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7,
'Class': 'First'}
print ("Variable Type : %s"
% type (dict))
Output:
Variable Type : <type 'dict'>
Methods:
1)dict.clear():Removes all
elements of dictionary dict
Example:
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Start Len : %d" % len(dict))
dict.clear()
print ("End Len : %d" % len(dict))
Output:
Start Len : 2
End Len : 0
2)dict.copy():Returns a shallow
copy of dictionary dict
Example:
#!/usr/bin/python3
dict1 = {'Name': 'Manni', 'Age': 7,
'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary :
",dict2)
Output:
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
3)dict. fromkeys():Create a new
dictionary with keys from seq and values set to value.
Syntax
Following is the syntax for fromkeys() method −
dict.fromkeys(seq[, value]))
Parameters
- seq − This is the list of values which would be used for
dictionary keys preparation.
- value − This is optional, if provided then value would be set to
this value
Return Value
This method returns the list.
Example:
#!/usr/bin/python3
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s"
% str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s"
% str(dict))
Output:
New Dictionary : {'age': None, 'name':
None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10,
'sex': 10}
4)dict. get():For key key,
returns value or default if key not in dictionary
Syntax
Following is the syntax for get() method –
dict.get(key,
default=None)
Parameters
· key − This is the Key to
be searched in the dictionary.
· default − This is the Value
to be returned in case key does not exist.
Return Value
This method
return a value for the given key. If key is not available, then returns default
value None.
Example:
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
Output:
Value
: 27
Value
: NA
5)dict.items(): Returns a list
of dict's (key, value) tuple pairs
Example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
Output:
Value
: [('Age', 7), ('Name', 'Zara')]
6)dict.keys():Returns list of
dictionary dict's keys
Example:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
Output:
Value : dict_keys(['Name', 'Age'])
7)dict. setdefault():The method
setdefault() is similar to get(), but will set dict[key] = default if key is
not already in dict.
Syntax
Following is the syntax for setdefault() method −
dict.setdefault(key, default = None)
Parameters
· key −
This is the key to be searched.
· default −
This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and
if given key is not available then it will return provided default value.
Example:
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)
Output:
Value
: 7
Value
: None
{'Name':
'Zara', 'Sex': None, 'Age': 7}
8)dict. update(dict2):The method update() adds dictionary dict2's key-values pairs
in to dict. This function does not return anything.
Example:
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)
Output:
updated dict : {'Sex': 'female', 'Age':
7, 'Name': 'Zara'}
9)dict. values():Returns list
of dictionary dict's values
Example:
#!/usr/bin/python3
dict = {'Sex': 'female', 'Age': 7,
'Name': 'Zara'}
print ("Values : ", list(dict.values()))
Output:
Values :
['female', 7, 'Zara']
Question:
What is the difference between a set and a dictionary?
A
set is an unordered data type which has no duplicate items inside it. a
dictionary arranges items as {"key": "value"} pairs. sets
are very handy when comparisons are to be made since sets handle data in a very
controlled way as they dont allow duplicates, but dicts are useful when we want
to store a bunch a data inside a single key, for example, all the cources
offered in a school could be values stored inside the key which could be the
school name, this is useful if we were handling large amount data that involved
working with all the schools of a region.
Dictionaries Related Programs and Questions:
=================== =================
1.
When does a dictionary is used instead of a list?
Dictionaries – are best suited when the data is labelled, i.e., the data is a record with field names.
Lists – are better option to store collections of un-labelled items say all the files and sub directories in a folder.
Generally Search operation on dictionary object is faster than searching a list object.
Dictionaries – are best suited when the data is labelled, i.e., the data is a record with field names.
Lists – are better option to store collections of un-labelled items say all the files and sub directories in a folder.
Generally Search operation on dictionary object is faster than searching a list object.
2.What are Python's
dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
3.How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
4.How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print (dict.keys()) # Prints all the keys
5.How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
3.How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
4.How will you get all the keys from the dictionary?
Using dictionary.keys() function, we can get all the keys from the dictionary object.
print (dict.keys()) # Prints all the keys
5.How will you get all the values from the dictionary?
Using dictionary.values() function, we can get all the values from the dictionary object.
print dict.values() # Prints all the values
6. Example of
dictionary
myDict = {'manish': 'bidsar','abc': 'efg'}
print(myDict)
print(myDict['manish'])
print(myDict["manish"])
myDict = {'manish': 'bidsar','abc': 'efg'}
print(myDict)
print(myDict['manish'])
print(myDict["manish"])
7.
Write a Python script to concatenate following dictionaries to create a new one
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
dic.update(d)
print(dic)
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
dic.update(d)
print(dic)
8.
Add key to dictionary
dict1
= {0:10, 1:20}
dict1[2]
= "30"
print(dict1)
9.
Write a Python program to iterate over dictionaries using for loops
d
= {"blue" : 1, "green" : 2, "yellow" : 3}
for
key,value in d.items():
print(key, value)
10.
Write a Python script to merge two Python dictionaries
d1
= {"a": "100", "b": "200"}
d2
= {"x": "4", "y": "500"}
d
= d1.copy()
d.update(d2)
print(d)
print(d1.keys())
print(d1)
print(d1.values())
11.
Write a Python program to get the maximum and minimum value in a dictionary.
my_dict
= {'x':500, 'y':5874, 'z': 560}
key_max
= max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min
= min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum
Value: ',my_dict[key_max])
print('Minimum
Value: ',my_dict[key_min])
#ALITER
values
= my_dict.values()
print(values)
min
= sorted(values)[0]
max
= sorted(values)[-1]
print(min)
print(max)
12.
Write a Python program to multiply all the items in a dictionary
#import
math
d
= {'n1': 5,'n2': 2,'n3': 3}
#print(mul.dict.vlaues())
res
= 1
for
key in d:
res= res*d[key]
print(res)
#ALITER
d
= {'n1': 5,'n2': 2,'n3': 3}
print(d.values())
res
= 1
for
i in d.values():
res=res*i
print(res)
print(d.items())
13.
Receiving tuples and dictionaries in functions
def powersum(power, *args):
total = 0
for i in args:
total += pow(i, power)
return total
powersum(2, 3, 4)
def powersum(power, *args):
total = 0
for i in args:
total += pow(i, power)
return total
powersum(2, 3, 4)
14.Write
a Python program to remove duplicates from Dictionary
dict
= {'one': 1, 'two': 2, 'three': 3, 'four': 1}
#print(dict)
#print(dict.items())
res
= {}
for
key,value in dict.items():
if value not in res.values():
res[key] = value
print(res)
15.
Write a Python program to check a dictionary is empty or not.
my_dict
= {}
if
not bool(my_dict):
print("Dictionary is empty")
else:
print("Dictionary is not empty")
16.Write
a Python program to combine two dictionary adding values for common keys
from
collections import Counter
d1
= {'a': 100, 'b': 200, 'c':300}
d2
= {'a': 300, 'b': 200, 'd':400}
d
= Counter(d1) + Counter(d2)
print(d)
17.
Write a Python program to print all unique values in a dictionary.
L
= [{"V":"S001"}, {"V": "S002"},
{"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
print("Original
List: ",L)
u_value
= set( val for dic in L for val in dic.values())
print("Unique
Values: ",u_value)
18.Write
a Python program to sort a dictionary by key.
color_dict
= {'red' : 1, 'blue': 2, 'orange': 3}
print(color_dict)
print(sorted(color_dict))
for
key in sorted(color_dict):
print("%s : %s" % (key, color_dict[key]))
19.Write
a Python program to sum all the items in a dictionary.
dict
= {'n1': 1, 'n2': 2, 'n3': 3}
print(sum(dict.values()))
20.
Write a Python script to concatenate following dictionaries to create a new one
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
dic.update(d)
print(dic)
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
dic.update(d)
print(dic)
21.
Add key to dictionary
dict1
= {0:10, 1:20}
dict1[2]
= "30"
print(dict1)
22.Example of
dictionary comprehension
from pprint import pprint as pp
country_to_capital = {'United kingdom': 'London','Brazil': 'Brazilia','Morocco': 'Rabat','Sweden': 'Stockholm'}
pp(country_to_capital.items())
capital_to_country = {capital: country for country, capital in country_to_capital.items()}
pp(capital_to_country)
from pprint import pprint as pp
country_to_capital = {'United kingdom': 'London','Brazil': 'Brazilia','Morocco': 'Rabat','Sweden': 'Stockholm'}
pp(country_to_capital.items())
capital_to_country = {capital: country for country, capital in country_to_capital.items()}
pp(capital_to_country)
23. Python Program to
Add a Key-Value Pair to the Dictionary
key=int(input("Enter the key (int) to be
added:"))
value=int(input("Enter the value for the key to
be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Output:
1:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}
2:
Enter the key (int) to be added:34
Enter the value for the key to be added:29
Updated dictionary is:
{34: 29}
24. Python Program to
Concatenate Two Dictionaries into One
d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
Output:
1:
Concatenated dictionary is:
{'A': 1, 'C': 3, 'B': 2}
25. Python Program to
Check if a Given Key Exists in a Dictionary or Not
d={'A':1,'B':2,'C':3}
key=input("Enter key to check:")
if key in d.keys():
print("Key
is present and value of the key is:")
print(d[key])
else:
print("Key
isn't present!")
Output:
1:
Enter key to check:A
Key is present and value of the key is:
1
2:
Enter key to check:F
Key isn't present!
26. Python Program to
Generate a Dictionary that Contains Numbers (between 1 and n) in the Form
(x,x*x).
n=int(input("Enter a number:"))
d={x:x*x for x in range(1,n+1)}
print(d)
Output:
1:
Enter a number:5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
2:
Enter a number:10
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8:
64, 9: 81, 10: 100}
27. Python Program to Sum All the Items in a Dictionary
d={'A':100,'B':540,'C':239}
print("Total sum of values in the
dictionary:")
print(sum(d.values()))
Output:
1:
Total sum of values in the dictionary:
879
28. Python Program to
Multiply All the Items in a Dictionary
d={'A':10,'B':10,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Output:
1:
23900
29. Python Program to
Remove the Given Key from a Dictionary
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key
not found!")
exit(0)
print("Updated dictionary")
print(d)
Output:
1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}
2:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!
30. Python Program to
Form a Dictionary from an Object of a Class
class A(object):
def __init__(self):
self.A=1
self.B=2
obj=A()
print(obj.__dict__)
Output:
1:
{'A': 1, 'B': 2}
31. Add key to
dictionary
keys=[]
values=[]
n=int(input("Enter number of elements for
dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter
element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter
element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Output:
1:
Enter number of elements for dictionary:3
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
For values:
Enter element1:1
Enter element2:4
Enter element3:9
The dictionary is:
{1: 1, 2: 4, 3: 9}
2:
Enter number of elements for dictionary:2
For keys:
Enter element1:23
Enter element2:46
For values:
Enter element1:69
Enter element2:138
The dictionary is:
{46: 138, 23: 69}
32. Python Program to
Count the Frequency of Words Appearing in a String Using a Dictionary
test_string=input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Output:
1.
Enter string: heloo heloo i am manish i am manish
you
{'heloo': 2, 'i': 2, 'am': 2, 'manish': 2, 'you': 1}
2:
Enter string:orange banana apple apple orange
pineapple
{'orange': 2, 'pineapple': 1, 'banana': 1, 'apple':
2}
33. Python Program to
Create a Dictionary with Key as First Character and Value as Words Starting
with that Character.
test_string=input("Enter string:")
l=test_string.split()
d={}
for word in l:
if(word[0]
not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,":",v)
Output:
1:
Enter string:python is my most favourite programming
language in the entire world
('e', ':', ['entire'])
('f', ':', ['favourite'])
('i', ':', ['in', 'is'])
('m', ':', ['most', 'my'])
('l', ':', ['language'])
('p', ':', ['programming', 'python'])
('t', ':', ['the'])
('w', ':', ['world'])
2.
Enter string: my name is manish
m : ['my', 'manish']
n : ['name']
i : ['is']
For Quick Recap on Dictionaries watch the below videos:
For Quick Recap on Dictionaries watch the below videos:
Very good explanation. Thank you for sharing. For More Information About Python Python Online Training
ReplyDeleteNice blog....useful information!
ReplyDeletePython Online Training Course
Python Developer Course Online Training
ReplyDeletePython-dictionary tutorial for beginners Free Learn By CodeExampler
C# for Loop Statement Learn Free for Beginners by CodeExampler website
ReplyDeleteNetworking And Scripting : Python Dictionaries And Dictionaries Programs >>>>> Download Now
ReplyDelete>>>>> Download Full
Networking And Scripting : Python Dictionaries And Dictionaries Programs >>>>> Download LINK
>>>>> Download Now
Networking And Scripting : Python Dictionaries And Dictionaries Programs >>>>> Download Full
>>>>> Download LINK rP