After lists and tuples, the next concept in Python is usually dictionaries.
Dictionaries are unordered collections of key-value pairs. They are mutable, meaning you can add, remove, and modify elements within them. Each element in a dictionary is accessed by its key rather than its index, which allows for efficient retrieval of values.
Here's an example of a dictionary in Python:
In this example, "name", "age", and "city" are the keys, and "John", 25, and "New York" are the corresponding values.
Dictionaries are commonly used for tasks such as storing and retrieving data, mapping values, and representing real-world objects or entities. They provide a flexible and powerful way to organize and manipulate data in Python.
Dictionaries are unordered collections of key-value pairs. They are mutable, meaning you can add, remove, and modify elements within them. Each element in a dictionary is accessed by its key rather than its index, which allows for efficient retrieval of values.
Here's an example of a dictionary in Python:
my_dict = {"name": "John", "age": 25, "city": "New York"}
In this example, "name", "age", and "city" are the keys, and "John", 25, and "New York" are the corresponding values.
Dictionaries are commonly used for tasks such as storing and retrieving data, mapping values, and representing real-world objects or entities. They provide a flexible and powerful way to organize and manipulate data in Python.
👍3
To get the value of a specific key in a dictionary, you can use the key as an index. Here's an example:
In this example, we access the values of the keys "name", "age", and "city" by using them as indices in square brackets. The corresponding values are then assigned to the variables
If the key does not exist in the dictionary, a
In this case, if the key "name" is found, its corresponding value is returned. If the key "country" is not found, the default value "Unknown" is returned instead of raising an error.
my_dict = {"name": "John", "age": 25, "city": "New York"}
name_value = my_dict["name"]
print(name_value) # Output: John
age_value = my_dict["age"]
print(age_value) # Output: 25
city_value = my_dict["city"]
print(city_value) # Output: New York
In this example, we access the values of the keys "name", "age", and "city" by using them as indices in square brackets. The corresponding values are then assigned to the variables
name_value, age_value, and city_value, respectively.If the key does not exist in the dictionary, a
KeyError will be raised. To avoid this, you can use the get() method, which allows you to provide a default value if the key is not found:my_dict = {"name": "John", "age": 25, "city": "New York"}
name_value = my_dict.get("name", "Unknown")
print(name_value) # Output: John
country_value = my_dict.get("country", "Unknown")
print(country_value) # Output: Unknown
In this case, if the key "name" is found, its corresponding value is returned. If the key "country" is not found, the default value "Unknown" is returned instead of raising an error.
👍2❤1
❤🔥8👍1
In Python, dictionaries are mutable data structures that allow you to store key-value pairs. One of the advantages of dictionaries is the ability to add and remove items dynamically.
To add an item to a dictionary, you can simply assign a value to a new or existing key. For example:
To remove an item from a dictionary, you can use the
It's important to note that if you try to remove a key that doesn't exist in the dictionary, a
Remember, dictionaries in Python are unordered, so the order of the items may not be the same as the order in which they were added.
To add an item to a dictionary, you can simply assign a value to a new or existing key. For example:
my_dict = {"apple": 3, "banana": 5}
my_dict["orange"] = 2
In this example, we added a new key-value pair "orange": 2 to the dictionary my_dict. If the key already exists, the value will be updated; otherwise, a new key-value pair will be created.To remove an item from a dictionary, you can use the
del keyword followed by the key you want to remove. For example:my_dict = {"apple": 3, "banana": 5, "orange": 2}
del my_dict["banana"]
In this example, we removed the key-value pair "banana": 5 from the dictionary my_dict using the del keyword.It's important to note that if you try to remove a key that doesn't exist in the dictionary, a
KeyError will be raised. To avoid this, you can use the dict.pop() method, which removes the item with the specified key and returns its value. For example:my_dict = {"apple": 3, "banana": 5, "orange": 2}
removed_value = my_dict.pop("banana")
In this example, the key-value pair "banana": 5 is removed from the dictionary my_dict, and the value 5 is assigned to the variable removed_value.Remember, dictionaries in Python are unordered, so the order of the items may not be the same as the order in which they were added.
👍3❤2
Forwarded from Kenasa
Eric_Matthes,_Python_Crash_Course_A_Hands_On,_Project_Based_Introduction.pdf
6.7 MB
👍2❤1
👍5
You can check if a key exists in a dictionary by using the
my_dict = {"dani": 3, "yohanes": 5}
print("eyob" in my_dict) # Output: False
in keyword. It returns True if the key is present, and False otherwise. For example:my_dict = {"dani": 3, "yohanes": 5}
print("eyob" in my_dict) # Output: False
my_dict = {"dani": 3, "eyob": 5, "bisrat": 2}
1.print(my_dict["bisrat"])
2.print("yohannes" in my_dict)
3.my_dict["dani"] = 4
4.print(len(my_dict))
5.del my_dict["eyob"]
Now, based on the code, can you answer the following questions about the dictionary?⚡1👍1
👍2
3. what is the use of the no.3 code
Anonymous Quiz
14%
none
79%
to change the key of the value 'dani' in the dictionary
7%
to change 'dani' to 3
☃3
5. what will be the output of the following code after the no.5 code run? print(my_dict)
Anonymous Quiz
9%
{"dani": 3, "eyob": 5, "bisrat": 2}
86%
{"dani": 3, "bisrat": 2}
5%
my_dict
Leetcode with dani
Can a dictionary have multiple values for the same key?
dictionary in Python cannot have multiple values for the same key. Each key in a dictionary must be unique, and it can only map to a single value.
If you try to assign a new value to an existing key in a dictionary, it will overwrite the previous value associated with that key. Here's an example:
If you try to assign a new value to an existing key in a dictionary, it will overwrite the previous value associated with that key. Here's an example:
my_dict = {"dani": 3, "abebe": 5, "yonas": 2}
my_dict["dani"] = 7 my_dict["kebe"] = 9
print(my_dict)
Output:{'dani': 7, 'abebe': 5, 'yonas': 2, 'kebe': 9}
As you can see, the value associated with the key "dani" has been updated from 3 to 7. The dictionary does not store multiple values for the same key.👍7❤1
Set in python
A set is an unordered collection of unique elements in Python. It is denoted by curly braces ({}) or by using the
Creating a set:
Adding elements to a set:
Removing elements from a set:
Set operations:
Sets are mutable, meaning you can modify them by adding or removing elements.
A set is an unordered collection of unique elements in Python. It is denoted by curly braces ({}) or by using the
set() function. Sets are useful when you want to store a collection of items without any duplicates and perform operations like union, intersection, and difference.Creating a set:
# Creating an empty set
my_set = set()
print(my_set) # Output: set()
# Creating a set with initial values
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
Adding elements to a set:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
# Adding multiple elements using update()
my_set.update([5, 6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
Removing elements from a set:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
# Removing an element that doesn't exist will raise an error
my_set.remove(6) # Raises KeyError
# Alternatively, you can use discard() to avoid errors
my_set.discard(6) # No error raised
Set operations:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union of two sets
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
# Intersection of two sets
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
# Difference between two sets
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
Sets are mutable, meaning you can modify them by adding or removing elements.
👍5
The similarities and differences between list, tuple, and set
1. Lists:
- Lists are ordered collections of items that can be modified (mutable).
- Elements in a list are enclosed in square brackets ().
- Lists allow duplicate elements.
- Elements in a list can be accessed using indexing and slicing.
- Lists are commonly used when you need to store and manipulate a collection of items that may change over time.
Example:
2. Tuples:
- Tuples are ordered collections of items that cannot be modified (immutable).
- Elements in a tuple are enclosed in parentheses ().
- Tuples allow duplicate elements.
- Elements in a tuple can be accessed using indexing and slicing, similar to lists.
- Tuples are commonly used when you want to store a collection of items that should not be changed, such as coordinates or database records.
Example:
3. Sets:
- Sets are unordered collections of unique elements.
- Elements in a set are enclosed in curly braces ({}) or created using the
- Sets do not allow duplicate elements. If you try to add a duplicate element, it will be ignored.
- Elements in a set cannot be accessed using indexing or slicing since they are unordered.
- Sets are commonly used when you need to store a collection of unique items and perform operations like union, intersection, and difference.
Example:
In summary, lists are mutable and allow duplicates, tuples are immutable and allow duplicates, while sets are mutable, unordered, and do not allow duplicates. The choice between them depends on the specific requirements of your program.
1. Lists:
- Lists are ordered collections of items that can be modified (mutable).
- Elements in a list are enclosed in square brackets ().
- Lists allow duplicate elements.
- Elements in a list can be accessed using indexing and slicing.
- Lists are commonly used when you need to store and manipulate a collection of items that may change over time.
Example:
my_list = [1, 2, 3, 4, 5]
2. Tuples:
- Tuples are ordered collections of items that cannot be modified (immutable).
- Elements in a tuple are enclosed in parentheses ().
- Tuples allow duplicate elements.
- Elements in a tuple can be accessed using indexing and slicing, similar to lists.
- Tuples are commonly used when you want to store a collection of items that should not be changed, such as coordinates or database records.
Example:
my_tuple = (1, 2, 3, 4, 5)
3. Sets:
- Sets are unordered collections of unique elements.
- Elements in a set are enclosed in curly braces ({}) or created using the
set() function.- Sets do not allow duplicate elements. If you try to add a duplicate element, it will be ignored.
- Elements in a set cannot be accessed using indexing or slicing since they are unordered.
- Sets are commonly used when you need to store a collection of unique items and perform operations like union, intersection, and difference.
Example:
my_set = {1, 2, 3, 4, 5}
In summary, lists are mutable and allow duplicates, tuples are immutable and allow duplicates, while sets are mutable, unordered, and do not allow duplicates. The choice between them depends on the specific requirements of your program.
👍6✍1🆒1
1. Which of the following collection types in Python is mutable?
Anonymous Quiz
23%
List
10%
Tuple
8%
Set
59%
A and C
2. What is the output of the following code snippet?
my_set = {1, 2, 3} my_set.add([4, 5]) print(my_set)
my_set = {1, 2, 3} my_set.add([4, 5]) print(my_set)
Anonymous Quiz
46%
{1, 2, 3, [4, 5]}
9%
{1, 2, 3, (4, 5)}
24%
TypeError: unhashable type: 'list'
21%
TypeError: unhashable type: 'set'
👍5
3. What is the output of the following code snippet?
set1 = {1, 2, 3} set2 = {3, 4, 5} result = set1 ^ set2 print(result)
set1 = {1, 2, 3} set2 = {3, 4, 5} result = set1 ^ set2 print(result)
Anonymous Quiz
8%
{1, 2}
4%
{2, 4, 5}
73%
{1, 2, 3, 4, 5}
15%
{1, 2, 4, 5}
👍1👏1