0% found this document useful (0 votes)
7 views34 pages

Python Dictionaries: Creation & Usage

Python programming Concepts - Dictionary

Uploaded by

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

Python Dictionaries: Creation & Usage

Python programming Concepts - Dictionary

Uploaded by

Kavitha Donepudi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

UNIT III - Dictionaries

Dr. [Link]
Creating Dictionary
 A dictionary is a collection of an unordered set of key:value pairs.
 Dictionaries are constructed using curly braces { }, wherein you include a list of
key:value pairs separated by commas.
 There is a colon (:) separating each of these key and value pairs.
 left of the colon -- keys
 right of the colon -- values.
 dictionaries are indexed by keys.
 Here a key along with its associated value is called a key:value pair.
 Dictionary keys are case sensitive. the keys are unique within a dictionary.
 Dictionary keys are immutable type and can be either a string or a number.
Duplicate keys are not allowed in the dictionary
Creating Dictionary
 dictionary_name = {key_1:value_1, key_2:value_2, key_3:value_3,
………,key_n:value_n}
 empty dictionary -- dictionary_name = { }
 pizza = {"pepperoni":3, "calzone":5, "margherita":4}
 mixed_dict = {"portable":"laptop", 9:11, 7:"julius"}
 The dict() Function: dict([**kwarg]) kwarg = value
 numbers = dict(one=1, two=2, three=3)
 Print(numbers)
 {'one': 1, 'two': 2, 'three': 3}
 The syntax for dict() function when iterables used is,
 dict(iterable[, **kwarg])
 1. >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
 {'sape': 4139, 'jack': 4098, 'guido': 4127}
Accessing and Modifying key:value Pairs in Dictionaries
 The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]
 The syntax for modifying the value of an existing key or for adding a new key:value
pair to a dictionary is, dictionary_name[key] = value
 the ordering of key:value pairs does not matter in dictionaries.
 Slicing is not allowed since they are not ordered like lists.
 Dictionaries remember the order in which the key:value pairs were inserted.
 check for the presence of a key in the dictionary using in and not in membership
 operators. It returns either a Boolean True or False value. For example,
 1. >>> clothes = {"rainy":"raincoats", "summer":"tees", "winter":"sweaters"}
 2. >>> "spring" in clothes
 False
 3. >>> "spring" not in clothes
 True
Populating Dictionaries with key:value Pairs
 1. start with an empty dictionary { }, then use the update() method to assign a
value to the key using assignment operator.
 1. >>> countries = {}
 2. >>> [Link]({"Asia":"India"})
 3. >>> [Link]({"Europe":"Germany"})
 5. >>> countries
 {'Asia': 'India', 'Europe': 'Germany'}
 6.>>>countries[‘Africa’] = “Zimbambwe”

 If the key does not exist, then the key:value pairs will be created automatically and
added to the dictionary
Removing an item from Dictionary
 To delete the key:value pair, use the del statement followed by the name of the dictionary
along with the key you want to delete.
 del dict_name[key]
 1. >>> animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
 2. >>> del animals["c"]
 3. >>> animals {'r': 'raccoon', 'm': 'moose'}
 Pop -- Removes the removes the key from the dictionary and returns its value.
 Animal = [Link](‘m’)
 popitem() -- removes and returns an arbitrary (key, value) tuple pair from the dictionary
 Popped = [Link]()
 clear() -- to remove all items from a dictionary at once.
 [Link]()
Traversing of Dictionary/Accessing an item

 A for loop can be used to iterate over keys or values or key:value pairs
in dictionaries.
 If you iterate over a dictionary using a for loop, then, by default, you
will iterate over the keys.
 If you want to iterate over the values, use values() method and for
iterating over the key:value pairs, specify the dictionary’s items()
method explicitly.
 The dict_keys, dict_values, and dict_items data types returned by
dictionary methods can be used in for loops to iterate over the keys or
values or key:value pairs.
Traversing of Dictionary
 1. currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen",
"Germany": "Euro"}
 2. def main():
 3. print("List of Countries")
 4. for key in [Link]():
 5. print(key)
 6. print("List of Currencies in different Countries")
 7. for value in [Link]():
 8. print(value)
 9. for key, value in [Link]():
 10. print(f"'{key}' has a currency of type '{value}'")
 11. if __name__ == "__main__":
 12. main()
Built-In Functions Used on Dictionaries

 Built-In Functions Used on Dictionaries


 Built-in Functions Description
 len() -- The len() function returns the number of items (key:value pairs) in a dictionary.
 all() -- The all() function returns Boolean True value if all the keys in the dictionary are
True else returns False.
 any() -- The any() function returns Boolean True value if any of the key in the dictionary
is True else returns False.
 sorted() -- The sorted() function by default returns a list of items, which are sorted
based on dictionary keys.
Built-In Functions Used on Dictionaries
 1. >>> presidents = {"washington":1732, "jefferson":1751, "lincoln":1809,
 "roosevelt":1858, "eisenhower":1890}
 2. >>> len(presidents)
 5
 3. >>> all_dict_func = {0:True, 2:False}
 4. >>> all(all_dict_func)
 False
 5. >>> all_dict_func = {1:True, 2:False}
 6. >>> all(all_dict_func)
 True
 7. >>> any_dict_func = {1:True, 2:False}
 8. >>> any(any_dict_func)
 True
Built-In Functions Used on
Dictionaries
 9. >>> sorted(presidents)
 ['eisenhower', 'jefferson', 'lincoln', 'roosevelt', 'washington']
 10. >>> sorted(presidents, reverse = True)
 ['washington', 'roosevelt', 'lincoln', 'jefferson', 'eisenhower']
 11. >>> sorted([Link]())
 [1732, 1751, 1809, 1858, 1890]
 12. >>> sorted([Link]())
 [('eisenhower', 1890), ('jefferson', 1751), ('lincoln', 1809), ('roosevelt',
1858),
 ('washington', 1732)]
Dictionary Methods
Tuples and Sets
 Tuple -- comprises an ordered, finite sequence of immutable, heterogeneous
elements that are of fixed sizes.
 tuple_name = (item_1, item_2, item_3, ………….., item_n)
 Empty tuple -- tuple_name = ()
 numbers = (1, 2, -5) letters = ("a", "b", "c")
 f1 = "ferrari", "redbull", "mercedes", "williams", "renault"
 You can store any item of type string, number, object, another variable, and
even another tuple itself
 mixed_tuple = (2, 'Hello', 'Python’, numbers)
 nested_tuples = (letters, numbers)
 A tuple with one item is constructed by having a value followed by a comma.
 stuple = 'hello',
Tuples
 tuple() Function --- tuple([sequence])
 S1 = ‘kavitha’
 St = tuple(S1)
 St = (‘k’,’a’,’v’,’i’,’t’,’h’,’a’)
 L1 = [1,2,’k’,’s’]
 Lt = tuple(L1)
 Lt = (1,2,’k’,’s’)
 T = (1,2,3,4)
 T1 = ()
 T1 += (1,)
 Item = int(input(‘enter tuple item:’))
 T1 += (item,)
 Tuples are:
 Ordered - They maintain the order of elements.
 Immutable - They cannot be changed after creation.
 Allow duplicates - They can contain duplicate values.
Basic Tuple Operations
 + operator to concatenate tuples together
 * operator to repeat a sequence of tuple items.
 == tuples are compared
 in and not in membership operators - check for the presence of an item in a tuple
 <, <=, >, >=, == and != are used to compare tuples - <, <=, >, >=, == and != are
used to compare tuples
Accessing Tuple Items
 Indexing and Slicing in Tuples
 tuple_name[index]
 tuple_name[start:stop[:step]]
 Traversing Tuple Items
 fruits = ('apple','banana','orange')
 for fruit in fruits:
 print(fruit)
 For fruit in range(len(fruits)):
 print(fruit)
 Tuple Immutable
 Fruits[0] = ‘grape’ --- not allowed
Built-In Functions Used on Tuples
 len() -- function returns the numbers of items in a tuple.
 sum() --- function returns the sum of numbers in the tuple.
 sorted() ---- function returns a sorted copy of the tuple as a list while leaving the original
tuple untouched. T1 = sorted(T)
 count() -- tuple_name.count(item) --- counts the number of times the item has occurred in
the tuple and returns it.
 index() -- tuple_name.index(item) --- searches for the given item from the start of the
tuple and returns its index. If the value appears more than once, you will get the index of
the first one. If the item is not present in the tuple, then ValueError is thrown by this
method
Tuple Packing and Unpacking
 The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
 1. >>> t = 12345, 54321, 'hello!'
 2. >>> t --- (12345, 54321, 'hello!')
 The values 12345, 54321 and 'hello!' are packed together into a tuple ➀–➁.
 Tuple Unpacking - The reverse operation of tuple packing is also possible.
 1. >>> x, y, z = t
 2. >>> x --- 12345
 3. >>> y --- 54321
 4. >>> z --- 'hello!'
 works for any sequence on the right-hand side.
 Tuple unpacking requires that there are as many variables on the left side of the equals
sign as there are items in the tuple
 2. a = int(input("Enter a value for first number "))
 3. b = int(input("Enter a value for second number "))
 4. b, a = a, b
 5. print("After Swapping")
 6. print(f"Value for first number {a}")
 7. print(f"Value for second number {b}")
Relation between Tuples and
Lists
 Tuples are immutable, cannot be added, removed or replaced in a tuple.

 Can contain a heterogeneous sequence


 elements are accessed via unpacking or indexing.
 If an item within a tuple is mutable, then you can change it
 Lists are mutable.
 items are accessed via indexing.
 convert a tuple to a list by passing the tuple name to the list() function.
 L1 = [1,2,3]
 T1= (4,5,6,L1)
Relation between Tuples and Dictionaries
 Tuples can be used as key:value pairs to build dictionaries.
 For example,
 1. >>> fish_weight_kg = (("white_shark", 520), ("beluga", 1571), ("greenland_shark", 1400))
 2. >>> fish_weight_kg_dict = dict(fish_weight_kg)
 3. >>> fish_weight_kg_dict
 {'white_shark': 520, 'beluga': 1571, 'greenland_shark': 1400}
 The tuples can be converted to dictionaries by passing the tuple name to the dict() function.
 This is achieved by nesting tuples within tuples, wherein each nested tuple item should have
two items in it
zip() Function
 The zip() function makes a sequence that aggregates elements from each of the iterables (can
 be zero or more). The syntax for zip() function is,
 zip(*iterables)
 An iterable can be a list, string, or dictionary. It returns a sequence of tuples, where the i-th
 tuple contains the i-th element from each of the iterables. The aggregation of elements stops
 when the shortest input iterable is exhausted.
 1. >>> x = [1, 3, 5]
 2. >>> y = [2, 4, 6]
 3. >>> zipped = zip(x, y)
 4. >>> list(zipped)
 [(1, 2), (3, 4), (5, 6)]
 For o,e in zip(x,y):
 print(o,e)
Sets
 A set is an unordered collection with no duplicate items.
 A set is a collection of unique items.
 basket = {'apple', 'orange', 'pear', 'banana'}
 set() function can be used to create sets with a comma-separated list of items inside
curly brackets { }.
 Note: to create an empty set you have to use set()
 not { } as this creates an empty dictionary.
 Sets support mathematical operations, such as union, intersection, difference, and
symmetric difference.
 Sets are mutable. Indexing is not possible in sets, since set items are unordered
 A = {'d', 'a', 'b', 'r', 'c'}
 B = {'m', 'l', 'c', 'z', 'a'}
 a – b -- {'b', 'r', 'd'}
 a | b -- {'l', 'm', 'z', 'd', 'a', 'b', 'r', 'c'}
 A & b -- {'a', 'c'}
 a ^ b -- {'l', 'd', 'm', 'b', 'r', 'z'}
 len(basket) -- 4
 sorted(basket) -- ['apple', 'banana', 'orange', 'pear']
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
 {'pear', 'orange', 'banana', 'apple'}
Set Methods
Set Methods
 1. >>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}

 2. >>> american_flowers = {"roses", "tulips", "lilies", "daisies"}

 3. >>> american_flowers.add("orchids")

 4. >>> american_flowers.difference(european_flowers) {'lilies', 'orchids', 'daisies'}

 5. >>> american_flowers.intersection(european_flowers) {'roses', 'tulips'}

 6. >>> american_flowers.isdisjoint(european_flowers) False

 7. >>> american_flowers.issuperset(european_flowers) False

 8. >>> american_flowers.issubset(european_flowers) False

 9. >>> american_flowers.symmetric_difference(european_flowers)

 {'lilies', 'orchids', 'daisies', 'goldcrest', 'sunflowers', 'lavender'}


Set Methods
 10. >>> american_flowers.union(european_flowers)

 {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}


 11. >>> american_flowers.update(european_flowers)
 12. >>> american_flowers
 {'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}
 13. >>> american_flowers.discard("roses")
 14. >>> american_flowers
 {'lilies', 'tulips', 'orchids', 'daisies'}
 15. >>> european_flowers.pop() 'tulips'
 16. >>> american_flowers.clear()
 17. >>> american_flowers
 set()
 Traversing of Sets
 iterate through each item in a set using a for loop.
 Frozenset
 Frozenset -- immutable -- can be used as members in other sets and as dictionary
keys
 The frozensets have the same functions as normal sets, except none of the functions
that change the contents (update, remove, pop,
 etc.) are available
Lists
 • Lists are a basic and useful data structure built into the Python language.

 • Built-in functions include len(), which returns the length of the list; max(), which returns
the maximum element in the list; min(), which returns the minimum element in the list
and sum(), which returns the sum of all the elements in the list.

 • An individual elements in the list can be accessed using the index operator [].

 • Lists are mutable sequences which can be used to add, delete, sort and even reverse
list elements.

 • The sort() method is used to sort items in the list.

 • The split() method can be used to split a string into a list.

 • Nested list means a list within another list.


Dictionary
 • A dictionary associates a set of keys with values.

 • The built-in function dict() returns a new dictionary initialized from an optional
keyword argument and a possibly empty set of keyword arguments.

 • The for loop is used to traverse all the keys in the dictionary.

 • The del dictionaryName[key] statement is used to delete an item for the given key.

 • Dictionary methods like keys(), values(), and items() are used to retrieve the values.

 • Methods like pop() and update() are used to manipulate the dictionary key:value
pairs.
Sets and Tuples
 • Tuple is an immutable data structure comprising of items that are ordered and heterogeneous.

 • Tuples are formed using commas and not the parenthesis.

 • Indexing and slicing of items are supported in tuples.

 • Tuples support built-in functions such as len(), min(), and max().

 • The set stores a collection of unique values and are not placed in any particular order.

 • Add an item to the set using add() method and remove an item from the set using the
remove() method.

 • The for loop is used to traverse the items in a set.

 • The issubset() or issuperset() method is used to test whether a set is a superset or a subset of
another set.

 • Sets also provide functions such as union(), intersection(), difference(), and


symmetric_difference().

You might also like