Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Dictionaries
Team Emertxe
Dictionaries
Introduction
Group of items arranged in the form of key-value pair
Example
d = {"Name": "Ram", "ID": 102, "Salary": 10000}
Program
#Print the entire dictionary
print(d)
#Print only the keys
print("Keys in dic: ", d.keys())
#Print only values
print("Values: ", d.values())
#Print both keys and value pairs as tuples
print(d.items())
Dictionaries
Operations
d = {"Name": "Ram", "ID": 102, "Salary": 10000}
1. To get the no. of pairs in the Dictionary n = len(d)
2. To modify the existing value d[salary] = 15000
3. To insert new key:value pair d["Dept"] = "Finance"
4. To delete the key:value pair del d["ID"]
5. To check whether the key is present in
dictionary
"Dept" in d
- Returns True, if it is present
6. We can use any datatype fro values, but keys should obey the rules
R1: Keys should be unique
Ex: emp = {10: "Ram", 20: "Ravi", 10: "Rahim"}
- Old value will be overwritten,
emp = {10: "Rahim", 20: "Ravi"}
R2: Keys should be immutable type. Use numbers, strings or tuples
If mutable keys are used, will get 'TypeError'
Dictionaries
Methods
clear() d.clear() Removes all key-value pairs from the d
copy() d1 = d.copy() Copies all items from ‘d’ into a new dictionary ‘d1’
fromkeys() d.fromkeyss(s, [,v])
Create a new dictionary with keys from sequence ‘s’ and
values all set to ‘v’
get() d.get(k, [,v])
Returns the value associated with key ‘k’.
If key is not found, it returns ‘v’
items() d.items()
Returns an object that contains key-value pairs of ‘d’.
The pairs are stored as tuples in the object
keys() d.keys() Returns a sequence of keys from the dictionary ‘d’
values() d.values() Returns a sequence of values from the dictionary ‘d’
update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’
pop() d.pop(k, [,v]) Removes the key ‘k’ and its value.
Dictionaries
Programs
To create the dictionary with employee details
d = {"Name": "Ram", "ID": 1023, "Salary": 10000}
#Print the entire dictionary
print(d)
#Print only the keys
print("Keys in dic: ", d.keys())
#Print only values
print("Values: ", d.values())
#Print both keys and value pairs as tuples
print(d.items())
Dictionaries
Programs
#To create a dictionary from the keyboard and display the items
x = {}
print("Enter 'n' value: ", end='')
n = int(input())
for i in range(n):
print("Enter the key: ", end='')
k = input()
print("Enter the value: ", end='')
v = int(input())
x.update({k: v})
print(x)
Dictionaries
Using for loop with Dictionaries
Method-1
for k in colors:
print(k)
Method-2
for k in colors:
print(colors[k])
Method-3
for k, v in colors.items():
print("key = {}nValue = {}". format(k, v))
Dictionaries
Sorting Dictionaries: Exercise
To sort the elements of a dictionary based on akey or value
Dictionaries
Converting Lists into Dictionary
Two step procedure
- zip()
- dict()
#To convert list into dictionary
countries = ["India", "USA"]
cities = ["New Delhi", "Washington"]
#Make a dictionary
z = zip(countries, cities)
d = dict(z)
print(d)
Dictionaries
Converting strings into dictionary
str = "Ram=23,Ganesh=20"
#Create the empty list
lst = []
for x in str.split(','):
y = x.split('=')
lst.append(y)
#Convert into dictionary
d = dict(lst)
print(d)
Dictionaries
Passing dictionary to function
By specifying the name of the dictionary as the parameter, we can pass the dictionary to the
function.
Example
d = {10: "Ram"}
display(d)
Dictionaries
Ordered Dictionaries
from collections import OrderedDict
Example
d = {10: "Ram"}
display(d)
Program:
#To create the ordered dictionary
from collections import OrderedDict
#Create empty dictionary
d = OrderedDict()
d[10] = 'A'
d[11] = 'B'
d[12] = 'C'
d[13] = 'D'
print(d)
THANK YOU

More Related Content

Python : Dictionaries

  • 2. Dictionaries Introduction Group of items arranged in the form of key-value pair Example d = {"Name": "Ram", "ID": 102, "Salary": 10000} Program #Print the entire dictionary print(d) #Print only the keys print("Keys in dic: ", d.keys()) #Print only values print("Values: ", d.values()) #Print both keys and value pairs as tuples print(d.items())
  • 3. Dictionaries Operations d = {"Name": "Ram", "ID": 102, "Salary": 10000} 1. To get the no. of pairs in the Dictionary n = len(d) 2. To modify the existing value d[salary] = 15000 3. To insert new key:value pair d["Dept"] = "Finance" 4. To delete the key:value pair del d["ID"] 5. To check whether the key is present in dictionary "Dept" in d - Returns True, if it is present 6. We can use any datatype fro values, but keys should obey the rules R1: Keys should be unique Ex: emp = {10: "Ram", 20: "Ravi", 10: "Rahim"} - Old value will be overwritten, emp = {10: "Rahim", 20: "Ravi"} R2: Keys should be immutable type. Use numbers, strings or tuples If mutable keys are used, will get 'TypeError'
  • 4. Dictionaries Methods clear() d.clear() Removes all key-value pairs from the d copy() d1 = d.copy() Copies all items from ‘d’ into a new dictionary ‘d1’ fromkeys() d.fromkeyss(s, [,v]) Create a new dictionary with keys from sequence ‘s’ and values all set to ‘v’ get() d.get(k, [,v]) Returns the value associated with key ‘k’. If key is not found, it returns ‘v’ items() d.items() Returns an object that contains key-value pairs of ‘d’. The pairs are stored as tuples in the object keys() d.keys() Returns a sequence of keys from the dictionary ‘d’ values() d.values() Returns a sequence of values from the dictionary ‘d’ update() d.update(x) Adds all elements from dictionary ‘x’ to ‘d’ pop() d.pop(k, [,v]) Removes the key ‘k’ and its value.
  • 5. Dictionaries Programs To create the dictionary with employee details d = {"Name": "Ram", "ID": 1023, "Salary": 10000} #Print the entire dictionary print(d) #Print only the keys print("Keys in dic: ", d.keys()) #Print only values print("Values: ", d.values()) #Print both keys and value pairs as tuples print(d.items())
  • 6. Dictionaries Programs #To create a dictionary from the keyboard and display the items x = {} print("Enter 'n' value: ", end='') n = int(input()) for i in range(n): print("Enter the key: ", end='') k = input() print("Enter the value: ", end='') v = int(input()) x.update({k: v}) print(x)
  • 7. Dictionaries Using for loop with Dictionaries Method-1 for k in colors: print(k) Method-2 for k in colors: print(colors[k]) Method-3 for k, v in colors.items(): print("key = {}nValue = {}". format(k, v))
  • 8. Dictionaries Sorting Dictionaries: Exercise To sort the elements of a dictionary based on akey or value
  • 9. Dictionaries Converting Lists into Dictionary Two step procedure - zip() - dict() #To convert list into dictionary countries = ["India", "USA"] cities = ["New Delhi", "Washington"] #Make a dictionary z = zip(countries, cities) d = dict(z) print(d)
  • 10. Dictionaries Converting strings into dictionary str = "Ram=23,Ganesh=20" #Create the empty list lst = [] for x in str.split(','): y = x.split('=') lst.append(y) #Convert into dictionary d = dict(lst) print(d)
  • 11. Dictionaries Passing dictionary to function By specifying the name of the dictionary as the parameter, we can pass the dictionary to the function. Example d = {10: "Ram"} display(d)
  • 12. Dictionaries Ordered Dictionaries from collections import OrderedDict Example d = {10: "Ram"} display(d) Program: #To create the ordered dictionary from collections import OrderedDict #Create empty dictionary d = OrderedDict() d[10] = 'A' d[11] = 'B' d[12] = 'C' d[13] = 'D' print(d)