Dictionary in python Dictionary in python Dictionary in pDictionary in python ython
sumanthcmcse
33 views
25 slides
Oct 04, 2024
Slide 1 of 25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
About This Presentation
python
Size: 127.82 KB
Language: en
Added: Oct 04, 2024
Slides: 25 pages
Slide Content
Dictionary in Python
What is a Dictionary in Python? A Dictionary in Python is the unordered, and changeable collection of data values that holds key-value pairs . Each key-value pair in the dictionary maps the key to its associated value. Python Dictionary is classified into two elements: Keys and Values. Keys will be a single element. Values can be a list or list within a list, numbers, etc.
Cont.. Dictionary is ordered or unordered? As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. Unordered means that the items does not have a defined order, you cannot refer to an item by using an index. Dictionary is Changeable: Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created. Duplicates Not Allowed in dictionary: Dictionaries cannot have two items with the same key
How to Create a Dictionary in Python? Dictionary is created with curly brackets, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:), while commas separate each element. A Dictionary in python is declared by enclosing a comma-separated list of key-value pairs using curly braces({}). Dictionaries are used to store data values in key:value pairs. #Creating an empty dictionary d = {} #Creating an empty dictionary with the dict function d = dict ()
Cont … # Initializing a dictionary with values a = { "a" :1 ,"b" :2} b = { 'fruit' : 'apple', ‘color' : ‘red’} c = { 'name' : ‘ Suchith ', 'age’ : 20} d = { 'name' : ‘ Ishanth ’, ‘ sem ’ : [1,2,3,7]} e = { ‘ branch’ :‘CSE ’, ‘course’ :[‘ c’,’java’,’python ’]} f = { 'a' :1, 'b' :2, 'c' :3, 'd’ :2} # For Sequence of Key-Value Pairs g = dict ([ (1, ‘Apple'), (2, 'Orange'), (3, 'Kiwi') ])
Properties of Dictionary Keys Keys must be unique: More than one entry per key is not allowed ( no duplicate key is allowed ) The values in the dictionary can be of any type , while the keys must be immutable like numbers, tuples, or strings. Dictionary keys are case sensitive - Same key name but with the different cases are treated as different keys in Python dictionaries.
How to Access Python Dictionary items? Since t he dictionary is an unordered collection, we can access the values using their keys. It can be done by placing the key in the square brackets or using the get function. Ex: Dname [ key ] or Dname. get ( key ) If we access a non-existing one , T he get function returns none . T he key inside a square brackets method throw an error .
Cont.. # Accessing dictionary items >>> a = {'name': 'Kevin', 'age': 25, 'job': 'Developer’} >>> len (a) #length of dictionary 3 # using get() >>> print("Name : ", a.get ('name’)) Name : Kevin >>> print("Age : ", a.get ('age’)) Age : 25 >>> print("Job : ", a.get ('job’)) Job : Developer
Insert and Update Dictionary items Remember, dicts are mutable, so you can insert or update any element at any point in time. Use the below syntax to insert or update values. DName [key] = value If a key is present, it updates the value. If DName does not have the key, then it inserts the new one with the given. >>> da = {'name': 'Kevin', 'age': 25} # Print Elements >>> print("Items : ", da) Items : {'name': 'Kevin', 'age': 25} # Add an Item >>> da['job'] = 'Programmer' >>> print("\ nItems : ", da) Items : {'name': 'Kevin', 'age': 25, 'job': 'Programmer’} # Update an Item >>> da['name'] = 'Python' >>> print("\ nItems : ", da) Items : {'name': 'Python', 'age': 25, 'job': 'Programmer'}
Methods in Python Dictionary Functions Description clear() Removes all Items copy() Returns Shallow Copy of a Dictionary fromkeys () Creates a dictionary from the given sequence get() Find the value of a key items() Returns view of dictionary’s (key, value) pair keys() Prints the keys popitem () Remove the last element of the dictionary setdefault () Inserts Key With a Value if Key is not Present pop() Removes and returns element having given key values() Returns view of all values in the dictionary update() Updates the Dictionary
Cont.. keys(): The keys() method returns a list of keys in a Python dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.keys () dict_keys (['name', 'age', 'job']) values(): The values() method returns a list of values in the dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> dict4.values() dict_values (['Python', 25, 'Programmer'])
Cont.. items(): This method returns a list of key-value pairs. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.items () dict_items ([(' name','Python '),('age',25),(' job','Programmer ')]) get(): It takes one to two arguments. While the first is the key to search for, the second is the value to return if the key isn’t found. The default value for this second argument is None. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.get ('job') 'Programmer' >>> d.get ("role") >>> d.get (" role","Not Present") 'Not Present'
Cont.. copy(): Python dictionary method copy() returns a shallow copy of the dictionary. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d2= d.copy () >>> d {'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d2 {'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> id(d) 3218144153792 >>> id(d2) 3218150637248
Cont.. pop(): This method is used to remove and display an item from the dictionary. It takes one or two arguments. The first is the key to be deleted, while the second is the value that’s returned if the key isn’t found. >>> d ={'name': 'Python', 'age': 25, 'job': 'Programmer’} >>> d.pop ("age") 25 >>> d {'name': 'Python', 'job': 'Programmer'} >>> d.pop ("role") Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> d.pop ("role") KeyError : 'role' >>> d.pop ("role",-1) -1
Cont.. p opitem (): The popitem () method removes and returns the item that was last inserted into the dictionary. >>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26} >>> d.popitem () ('age', 26) fromkeys (): Python dictionary method fromkeys () creates a new dictionary with keys from seq and values set to value. >>> d= fromkeys ({1,2,3,4,7},0) >>> d {1: 0, 2: 0, 3: 0, 4: 0, 7: 0} >>> seq = ('name', 'age', ‘job’) >>> d2 = d2.fromkeys(seq) >>> d2 {'age': None, 'name': None, ‘job': None}
Cont.. update (): The update() method takes another dictionary as an argument. Then it updates the dictionary to hold values from the other dictionary that it doesn’t already. >>> d1 ={'name': 'Python', 'job': 'Programmer’} >>> d2 ={ 'age’: 26} >>> d1.update(d2) >>> print(d1) {'name': 'python', 'job': 'programmer', 'age': 25} >>> d1 ={'name': 'Python', 'job': 'Programmer’} >>> d2 ={ 'age’: 26, 'name’: ‘Java'} >>> d1.update(d2) >>> print(d1) {'name’: ‘Java', 'job': 'programmer', 'age': 25} clear(): Removes all elements of dictionary. >>> d ={'name': 'Python', 'job': 'Programmer’, 'age’: 26} >>> d.clear () {}
Cont.. setdefault (): Returns the value of the specified key in the dictionary. If the key not found, then it adds the key with the specified defaultvalue . If the defaultvalue is not specified then it set None value. Syntax: dict.setdefault (key, defaultValue ) Ex: romanNums = {'I':1, 'II':2, 'III':3} romanNums.setdefault ('IV') print( romanNums ) {'I': 1, 'II': 2, 'III': 3, 'IV': None} romanNums.setdefault ('VI', 4) print( romanNums ) {'I': 1, 'II': 2, 'III': 3, 'IV': 4}
Iterating Dictionary A dictionary can be iterated using for loop as given below. # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} for i in Employee: print( i ) Output: Name Age salary Company
Iterating Dictionary # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} Output: Kiran 29 25000 GOOGLE for i in Employee.values (): print( i ) for i in Employee: print( Employee[ i ] ) Output: Kiran 29 25000 GOOGLE
Iterating Dictionary A dictionary can be iterated using for loop as given below. # for loop to print all the keys of a dictionary Employee = {"Name": “Kiran", "Age": 29, "salary":25000, "Company":"GOOGLE"} for i in Employee.items (): print( i ) Output: ('Name', 'Kiran') ('Age', 29) ('salary', 25000) ('Company', 'GOOGLE')
Difference between List and Dictionary in Python Comparison Parameter List Dictionary Definition Collection of various elements just like an array. Collection of elements in the hashed structure as key-value pairs Syntax Placing all the elements inside square brackets [], separated by commas(,) Placing all key-value pairs inside curly brackets({}), separated by a comma. Also, each key and pair is separated by a semi-colon (:) Index type Indices are integer values starts from value 0 The keys in the dictionary are of any given data type Mode of Access We can access the elements using the index value We can access the elements using the keys Order of Elements The default order of elements is always maintained No guarantee of maintaining the order Mutability Lists are mutable in nature Dictionaries are mutable, but keys do not allow duplicates Creation List object is created using list() function Dictionary object is created using dict () function Sort() Sort() method sorts the elements in ascending or descending order Sort() method sorts the keys in the dictionary by default Count() Count() methods returns the number of elements appeared in list Count() method does not exists in dictionation Reverse() Reverse() method reverse the list elements Dictionary items cannot be reversed as they are the key-value pairs
Write a Python program to check whether a given key already exists in a dictionary. d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} key= int (input(“enter key element to be searched”)) if n in d: print("key present") else: print("Key not present")
Write a program to count the number of occurrences of character in a string. x = input("Enter a String: ") count = {} for ch in x: count.setdefault ( ch , 0) count[ ch ] = count[ ch ] + 1 print(count) Output: Enter a String: Kannada {'K': 1, 'a': 3, 'n': 2, 'd': 1}
Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. d= dict () for x in range(1,16): d[x]=x**2 print(d) Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}