Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Dictionary in Python-1

Uploaded by

PRASHANT MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Dictionary in Python-1

Uploaded by

PRASHANT MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Dictionary in python

• List_ in_list = [
• [1, 2, 3],
• [4, 5, 6],
• [7, 8, 9]
•]

• # Accessing elements
• print(List_ in_list [0][0]) # Output: 1
• print(List_ in_list [1][2]) # Output: 6

• # Printing the matrix


• for row in List_ in_list :
• print(row)
• find index of nth occurrence of any element
• t1 =(1,2,2,3,3,3,2,2)
• elem = int(input("enter the element for which we want find the index" ))
• n = int(input("enter the occurence"))
• count = 0
• y=-1
• for i in t1:
• y=y+1

• if i == elem:
• count = count+1
• #print("hIIIII sangita")
• #print("hello", count)
• if count == n:
• print("kumari")
• # print(count)
• print("MCTE",y)
• break

index()
• The index() function in Python is a built-in method used with
sequences like lists, strings, and tuples to find the first occurrence of a
specified value.
• When the value is found, it returns the index of the item. If the value
is not found, it raises a ValueError.
• Syntax:
• list.index(element, start, end)
• tuple.index(element, start, end)
• For string
• str.index(substring, start, end)
• Parameters : element / substring: The element or substring to search
for.
• start (optional): The starting index from where the search begins.
Default is 0.
• end (optional): The ending index where the search ends. Default is
the end of the sequence.

• Return Value: The index() function returns the index of the first
occurrence of the specified value. If the value is not found, it raises a
ValueError.
• my_list = [1, 2, 3, 4, 3, 5]
• print(my_list.index(3)) # Output: 2
• print(my_list.index(3, 3, 6)) # Output: 4
• # print(my_list.index(6)) # Raises ValueError
• my_tuple = ('a', 'b', 'c', 'd', 'b')
• print(my_tuple.index('b')) # Output: 1
• print(my_tuple.index('b', 2, 5)) # Output: 4
• # print(my_tuple.index('z')) # Raises ValueError
• my_string = "hello world"
• print(my_string.index('o')) # Output: 4
• print(my_string.index('o', 5)) # Output: 7
• print(my_string.index('world')) # Output: 6
• # print(my_string.index('x')) # Raises ValueError
can i pass a list that contains two list as argument in set() in not then why?

• You cannot pass a list that contains other lists as an argument to the
set() function in Python. This is because sets require their elements to
be hashable, and lists are mutable and therefore not hashable.
• Explanation
• Hashable Objects: In Python, an object is hashable if it has a hash
value that does not change during its lifetime. Hashable objects can
be compared to each other and used as keys in a dictionary or as
elements of a set.
• Mutable Objects: Lists in Python are mutable, meaning their contents
can change after they are created. This mutability means they do not
have a fixed hash value and are therefore not hashable.
• list_of_lists = [[1, 2], [3, 4]]
• my_set = set(list_of_lists) # This will raise a TypeError

• Solution
• If you need to create a set from a list of lists, you can convert the
inner lists to tuples (which are immutable and hashable) before
passing them to the set() function:
• list_of_lists = [[1, 2], [3, 4]]
• list_of_tuples = [tuple(inner_list) for inner_list in list_of_lists]
• my_set = set(list_of_tuples)

• print(my_set) # Output: {(1, 2), (3, 4)}


• Explanation of the Solution
• Convert Inner Lists to Tuples: Use a list comprehension to iterate
through each inner list and convert it to a tuple.
• Create a Set: Pass the list of tuples to the set() function.By converting
the inner lists to tuples, you ensure that the elements are hashable,
allowing the set() function to create a set without raising an error.
• 1. Dictionaries are built in data types in python
• 2. dictionaries are used to store the data in key : value pairs
• 3. Unlike other sequential data types which are indexed by a range of
numbers, dictionaries are indexed by keys.
• 4. keys in a dictionary can be any immutable type; like strings and
numbers.
• 5. Tuples can be used as keys if they contain only strings, numbers or
tuples .
• 6. If a tuple contains any mutable object either directly or indirectly it
cannot be used as a key.
• 7. you can not use lists as keys, since lists can be modified in place
using index assignments, slice assignments or methods like append()
and extend().
• 8. Mutable : We can add, remove, and change items after the
dictionary has been created.
• 9. Dynamic Size : Dictionaries can grow and shrink as needed, as we
can add or remove key value pair.
• 10. Efficient lookups : Dictionaries are implemented using hash tables,
providing average O(1) time Complexity For lookups, insertion, and
deletions.
• 11. Flexible Value Types: Values in a Dictionary can be of any
datatype, including other dictionaries, lists, sets, or even custom
objects.
• 12. Comprehensions: Python Supports dictionary comprehensions,
which allow you to create dictionaries in a concise and readable
manner.
13. Methods : Dictionaries come with a variety of buit-in methods for
operations like retrieving keys keys(), values(), item(),pop(). And more.
• # Creating a Dictionary
• My_dict = {}
• My_dict = {'name' : “Ram", "age" : 30, "City" : "new York"}
• print(My_dict) #{'name': ‘Ram', 'age': 30, 'City': 'new York'}

• #adding a key – value pair


• My_dict[“job”] = “Engineer”
• print(My_dict) # {'name': ‘Ram', 'age': 30, 'City': 'new York', 'job': 'Engineer’}

#Modifying a value
• My_dict[“age”] = 31
• print(My_dict) # {'name': ‘Ram', 'age': 31, 'City': 'new York', 'job': 'Engineer’}

• #Removing a key value pair


• del My_dict[‘city’] # {'name': ‘Ram', 'age': 31, 'job': 'Engineer'}

• #checking if a key exists


• print(“name” in My-dict) #True
• # Accessing a value using a key
• value = my_dict['key1’]
• Print(value)

• # Updating an existing value


• my_dict['key1'] = 'new_value1’

• # Clearing all items from the dictionary


• my_dict.clear()
• # Getting a list of all keys
• keys = my_dict.keys()

• # Getting a list of all values


• values = my_dict.values()

• # Getting a list of all key-value pairs


• items = my_dict.items()
• # Getting a value with a default if the key does not exist
• value = my_dict.get('key1', 'default_value’)

• # Checking if a key exists in the dictionary


• exists = 'key1' in my_dict
Example
• d1={"name" : "sangita",
• "branch" : "CSE",
• "name" :"ram"
• }
• value = d1.get('score', 'default_value')
• print(value) Output: default_value

• A = "name" in d1
• print(A) Output: True
• #Iterating over keys and values
For key, value in My_dict.items():
print(f”{key} : {value}”)
# using a dictionary comprehension
Squares = {x: x*x for x in range(5)}
print(Squares)
Merging Dictionaries (Python 3.9+)
• dict1 = {'a': 1, 'b': 2}
• dict2 = {'b': 3, 'c': 4}
• merged_dict = dict1 | dict2
• print(merged_dict)

• Output: {'a': 1, 'b': 3, 'c': 4}


Copy () function
• # Shallow copy
• copy_dict = my_dict.copy()

• # Deep copy(for deep copy you need to import copy, for shallow we
not need to import anything)
• import copy
• deep_copy_dict = copy.deepcopy(my_dict)
• In Python, the difference between shallow and deep copy is how they
handle copying of nested objects. Let's break down the concepts and
see some examples to illustrate the difference.
• Shallow Copy
• A shallow copy of an object creates a new object, but inserts references
into it to the objects found in the original. This means that the copy is
only one level deep, and any changes to nested objects within the
copied object will reflect in the original object, and vice versa.
• Deep Copy
• A deep copy of an object creates a new object and recursively copies all
objects found in the original. This means that the copy is completely
independent of the original, and changes to nested objects within the
copied object will not affect the original object, and vice versa.
• import copy

• # Original list with nested objects


• original_list = [1, 2, [3, 4], 5]

• # Shallow copy of the list


• shallow_copy_list = copy.copy(original_list)

• # Deep copy of the list


• deep_copy_list = copy.deepcopy(original_list)

• # Modifying the nested list in the original list


• original_list[2][0] = 'changed'

• print("Original List:", original_list) # Output: [1, 2, ['changed', 4], 5]


• print("Shallow Copy List:", shallow_copy_list) # Output: [1, 2, ['changed', 4], 5]
• print("Deep Copy List:", deep_copy_list) # Output: [1, 2, [3, 4], 5]
Iterating over keys and values

for key, value in My_dict.items():


print(f"{key} : {value}")
Using a dictionary comprehension

• quares = {x: x*x for x in range(5)}


• print(squares)

• Output:
• {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Pop() function
• In Python, the pop() method in dictionaries is used to remove a
specified key and return its corresponding value. If the specified key is
not found, the method can return a default value if provided, or raise
a KeyError if no default value is specified.
• dict.pop(key,[ default])

• key: The key to be removed from the dictionary.


• default (optional): The value to return if the key is not found. If not
provided and the key is not found, a KeyError is raised.
Example
• # Define a dictionary
• my_dict = {'a': 1, 'b': 2, 'c': 3}

• # Remove and return the value for the key 'b'


• value = my_dict.pop('b')
• print(value) # Output: 2

• # Print the updated dictionary


• print(my_dict) # Output: {'a': 1, 'c': 3}
• # Define a dictionary
• my_dict = {'a': 1, 'b': 2, 'c': 3}

• # Attempt to remove and return the value for a non-existing key 'd' with a
default value
• value = my_dict.pop('d', 'Key not found')
• print(value) # Output: Key not found

• # Print the updated dictionary


• print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
• # Define a dictionary
• my_dict = {'a': 1, 'b': 2, 'c': 3}

• # Attempt to remove and return the value for a non-existing key 'd' with a default value
• value = my_dict.pop('d')
• print(value) # Output: Key not found

• # Print the updated dictionary


• print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}

• Output: KeyError: ‘d’


• throw an exception and stop the execution .
Summary
• The pop() method removes the specified key from the dictionary and
returns its value. If the key is not found, it can return a default value if
provided; otherwise, it raises a KeyError. This method is useful for
safely removing and retrieving values from a dictionary.
Nested Dictionary
• # Declaring a nested dictionary
• nested_dict = {
• 'key1': {
• 'nested_key1': 'nested_value1',
• 'nested_key2': 'nested_value2'
• },
• 'key2': {
• 'nested_key3': 'nested_value3',
• 'nested_key4': 'nested_value4'
• }
• }

• # Accessing a value in the nested dictionary


• value = nested_dict['key1']['nested_key1']
• print(value) # Output: nested_value1
• # Declaring a nested dictionary
• nested_dict = {
• 'key1': {
• 'name': 'Sangita',
• 'branch': 'CSE'
• },
• 'key2': {
• 'name': 'ram',
• 'branch': 'ECE'
• }
• }
• # Accessing a value in the nested dictionary
• value = nested_dict['key1']['name']
• value = nested_dict['key1']['branch']
• print(value) # Output: nested_value1

• for key, value in nested_dict.items():


• print("dictionary items",key,’:’value)
Tuple as key in DICT.
• In Python, you can use tuples as keys in a dictionary. This is possible
because tuples are immutable and hashable, making them valid keys.
• Using tuples as dictionary keys can be useful when you want to use a
combination of values to represent a single key. Here are some
examples to illustrate how to use tuples as keys in a dictionary.
example
• # Declaring a dictionary with tuple keys
• tuple_key_dict = {
• ('a', 1): 'value1',
• ('b', 2): 'value2',
• ('c', 3): 'value3'
•}

• # Accessing values using tuple keys


• print(tuple_key_dict[('a', 1)]) # Output: value1
• print(tuple_key_dict[('b', 2)]) # Output: value2
Example 3: Using Tuple Keys for Storing Coordinates
Tuples can be particularly useful as dictionary keys when dealing with coordinates
or other composite data.
• # Declaring a dictionary with tuple keys representing coordinates
• coordinate_dict = {
• (0, 0): 'origin',
• (1, 2): 'point1',
• (2, 3): 'point2',
• (-1, -1): 'point3'
• }

• # Accessing values using tuple keys


• print(coordinate_dict[(0, 0)]) # Output: origin
• print(coordinate_dict[(1, 2)]) # Output: point1

• # Adding a new key-value pair


• coordinate_dict[(3, 4)] = 'point4'
• print(coordinate_dict[(3, 4)]) # Output: point4
• # Declaring a dictionary with tuple keys representing coordinates
• coordinate_dict = {
• (0, 0): 'origin',
• (1, 2): 'point1',
• (2, 3): 'point2',
• (-1, -1): 'point3'
• }
• for key,value in coordinate_dict.items():
• print("myponits",key,':',value)

• Output: myponits (0, 0) : origin


• myponits (1, 2) : point1
• myponits (2, 3) : point2
• myponits (-1, -1) : point3
• myponits (3, 4) : point4

You might also like