تلخيص Tuples+ Dict
تلخيص Tuples+ Dict
تلخيص Tuples+ Dict
A tuple is a collection similar to a Python list. The primary difference is that we cannot modify a tuple once it is
created. (Tuples are “immutable”) ال يمكن تعديل محتواها
Tuples are another kind of sequence that functions much like a list - they have elements which are indexed starting at
0
Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string
Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of
memory use and performance than lists
So in our program when we are making “temporary variables” we prefer tuples over lists
Tuples are Comparable قابلة للمقارنة
We can take advantage of the ability to sort a list of tuples to get a sorted version of a dictionary
First we sort the dictionary by the key using the items() method and sorted() function
Functions: count , index
Tuple Characteristics
Tuples are:
print(numbers)
The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is at index 1, and so on.
Access Items Using Index
Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.
We use the len() function to find the number of items present in a tuple. For example,
We use the for loop to iterate over the items of a tuple. For example,
OUTPUT
Code Output
thistuple = ("apple", "banana", "cherry") ('apple', 'banana', 'cherry')
print(thistuple)
thistuple = ("apple", "banana", "cherry") 3
print(len(thistuple))
thistuple = ("apple",) <class 'tuple'>
print(type(thistuple))
thistuple = ("apple") <class 'str'>
print(type(thistuple))
tuple1 = ("apple", "banana", "cherry") ('apple', 'banana', 'cherry')
tuple2 = (1, 5, 7, 9, 3) (1, 5, 7, 9, 3)
tuple3 = (True, False, False) (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
(x, y) = (4, 'fred') 'fred'
print(y)
(a, b) = (99, 98) 99
print(a)
z = (5, 4, 3) Traceback:'tuple' object ال يمكن تعديل
z[2] = 0 does tuples عناصر
not support item
Assignment
print(f"{key}: {val}")
2. Write a python code with function returning multiple values as a tuple(add, subtract, multiply, divide)
# Function returning multiple values as a tuple
return (a + b, a - b, a * b, a / b)
result = calculate(10, 5)
Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by commas. For example,
The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the key and 'Berlin' is the value
assigned to it and so on.
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
We can iterate through dictionary keys one by one using a for loop.
Find Dictionary Length
We can find the length of a dictionary by using the len() function.
Python Dictionary Methods
We can use get() and provide a default value of zero when the key is not yet in the dictionary – and
items() Returns a list containing a tuple for each key value pair
Searching in Dictionary
We can check whether a key exists in a dictionary by using the in and not in operators.
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.
OUTPUT
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
counts = {'a': 3, 'b': 2, 'c': 5} {'a': 3, 'b': 5, 'c': 5}
counts['b'] = counts.get('b', 0) + 3
print(counts)
thisdict = { Ford
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 2020} يتم اخذ اخر
"brand": "Ford", قييمة اذا
"model": "Mustang", تكررت
"year": 1964, Key
"year": 2020 وليسvalue
}
print(thisdict)
thisdict = { 3 ال تحسبkey
"brand": "Ford", المكررة
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
thisdict = { 4
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"color": ‘black’
}
print(len(thisdict))
thisdict = { {'brand': 'Ford', 'model': 'Mustang', 'year': 2020, 'uid': 2020} تحسبvalue
"brand": "Ford", المكررة
"model": "Mustang",
"year": 2020,
"uid": 2020
}
print(thisdict)
thisdict = { {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red',
"brand": "Ford", 'white', 'blue']}
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
thisdict = { <class 'dict'>
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
thisdict = dict(name = "John", age = {'name': 'John', 'age': 36, 'country': 'Norway'}
36, country = "Norway")
print(thisdict)
cabinet = dict()
cabinet['summer'] = 12
cabinet['fall'] = 3
cabinet['spring'] = 75
print(cabinet) {'summer': 12, 'fall': 3, 'spring': 75}
3
print(cabinet['fall']) 3
cabinet['fall'] = cabinet['fall'] + 2
print(cabinet) {'summer': 12, 'fall': 5, 'spring': 75}
names = dict()
names['ahmad'] = 82
names['ali'] = 38
names['sami'] = 75
print('ahmad' in names) True
print('khaled' in names) False
thisdict = { Ford
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.get('brand')
print(x)
thisdict = { None
"brand": "Ford", غيرKey
"model": "Mustang", موجوده
"year": 1964
}
x = thisdict.get(‘color’)
print(x)
x = thisdict.keys()
print(x)
x = thisdict.values()
print(x)
x = thisdict.items()
print(x)
d = {1: 'Geeks', 2: 'For', 3:'Python'} 1 Geeks
for key,value in d.items(): 2 For
print(key,value) 3 Python
d = {1: 'Geeks', 2: 'For', 'age':22} 1
2
# Iterate over keys age
for key in d: Geeks
print(key) For
# Iterate over values 22
for value in d.values(): 1: Geeks
print(value) 2: For
for key, value in d.items(): age: 22
print(f"{key}: {value}")
Multiple Choices
a. student[0][1]
b. student[1]["age"] Answer: b
c. student[0]["age"]
d. None
7. In Python, Dictionaries are immutable
a. True Answer: a
b. False
8. Items are accessed by their position in a dictionary and All the keys in a dictionary must be of the same
type.
a. True
b. False Answer:b
9. Select the correct ways to get the value of marks key.
student = {
"name": "Emma",
"class": 9,
"marks": 75
}
a. m = student.get(2)
b. m = student.get('marks') Answer: b
c. m = student[2])
d. m = student['marks'])
10. What is the output of the following code
a. True Answer:a
b. False
Coding
1. Write a python code to count word frequencies in a line of entered text by user.
line = input("Enter a line of text: ")
words = line.split()
counts = {}
counts[word] = counts.get(word, 0) + 1
2. Write a python code to Find the most common word in a text entered by user .
Input Example:
Enter Text: Python is powerfull language, I love Python . I don't like C# language. Python
is better
Output:
The most common word is Python with 3 occurrences.
file_content = input("Enter Text: ")
words = file_content.split()
counts = {}
counts[word] = counts.get(word, 0) + 1
# Sorting by keys
sorted_by_keys = dict(sorted(data.items()))
b. By Values
# Sample dictionary
def value_extractor(item):
return item[1]
# Sorting by values
def add_student():
name = input("Enter student name: ")
if name in student_marks:
print("Student already exists.")
else:
marks = int(input("Enter marks: "))
student_marks[name] = marks
print("Added " + str(name) + " with " + str(marks) + " marks.")
def update_marks():
name = input("Enter student name to update: ")
if name in student_marks:
marks = int(input("Enter new marks: "))
student_marks[name] = marks
print("Updated " + str(name) + "'s marks to " + str(marks) )
else:
print("Student not found.")
def display_students():
if student_marks:
print("Students and their marks:")
for name, marks in student_marks.items():
print(name + "," + str(marks))
else:
print("No students found.")
def find_top_student():
if student_marks:
top_student = max(student_marks, key=student_marks.get)
print("Top student:" + str(top_student) + " with " +
str(student_marks[top_student]) + " marks." )
else:
print("No students found.")
def calculate_average():
if student_marks:
average = sum(student_marks.values()) / len(student_marks)
print(f"Average marks: {average:.2f}")
else:
print("No students found.")
def main():
while True:
print("\n--- Student Marks Management ---")
print("1. Add Student")
print("2. Update Marks")
print("3. Display All Students")
print("4. Find Top Student")
print("5. Calculate Average Marks")
print("6. Exit")
def add_salesperson():
name = input("Enter salesperson name: ")
if name in sales_data:
print("Salesperson already exists.")
else:
sales_amount = float(input("Enter sales amount: "))
tax_percentage = float(input("Enter tax percentage: "))
sales_data[name] = {"sales_amount": sales_amount, "tax_percentage": tax_percentage}
print(f"Added {name} with sales amount {sales_amount} and tax percentage
{tax_percentage}%.")
def update_salesperson():
def display_sales_data():
if sales_data:
print("Salesperson Data:")
for name, data in sales_data.items():
tax_amount = data["sales_amount"] * data["tax_percentage"] / 100
print(f"Name: {name}, Sales Amount: {data['sales_amount']}, Tax Percentage:
{data['tax_percentage']}%, Tax Amount: {tax_amount:.2f}")
else:
print("No sales data found.")
def find_top_salesperson():
if sales_data:
top_salesperson = max(sales_data, key=lambda name: sales_data[name]
["sales_amount"])
print(f"Top salesperson: {top_salesperson} with {sales_data[top_salesperson]
['sales_amount']} in sales.")
else:
print("No sales data found.")
def calculate_totals():
if sales_data:
total_sales = sum(data["sales_amount"] for data in sales_data.values())
total_tax = sum(data["sales_amount"] * data["tax_percentage"] / 100 for data in
sales_data.values())
print(f"Total sales: {total_sales:.2f}")
print(f"Total tax collected: {total_tax:.2f}")
else:
print("No sales data found.")
def main():
while True:
print("\n--- Salesperson Data Management ---")
print("1. Add Sales Data")
print("2. Update Sales Data")
print("3. Display All Sales Data")
print("4. Find Top Salesperson")
print("5. Calculate Total Sales and Tax")
print("6. Exit")
def add_salesperson():
name = input("Enter salesperson name: ")
if name in sales_data:
print("Salesperson already exists.")
else:
sales_amount = float(input("Enter sales amount: "))
tax_percentage = float(input("Enter tax percentage: "))
sales_data[name] = {"sales_amount": sales_amount, "tax_percentage":
tax_percentage}
print(f"Added {name} with sales amount {sales_amount} and tax percentage
{tax_percentage}%.")
def enter_marks():
name = input("Enter student name: ")
if name in student_marks:
print("Student already exists. Use option 1 to overwrite marks.")
else:
marks = float(input("Enter marks: "))
student_marks[name] = marks
print(f"Added {name} with marks {marks}.")
def display_students():
if student_marks:
print("Students and their marks:")
for name, marks in student_marks.items():
print(f"{name}: {marks}")
else:
print("No students found.")
def find_highest_marks():
if student_marks:
top_student = max(student_marks, key=student_marks.get)
print(f"Student with the highest marks: {top_student}
({student_marks[top_student]})")
else:
print("No students found.")
def find_lowest_marks():
if student_marks:
low_student = min(student_marks, key=student_marks.get)
print(f"Student with the lowest marks: {low_student}
({student_marks[low_student]})")
else:
print("No students found.")
def calculate_average_marks():
if student_marks:
average = sum(student_marks.values()) / len(student_marks)
print(f"Average marks: {average:.2f}")
else:
print("No students found.")
def main():
while True:
print("\n--- Student Marks Management ---")
print("1. Enter Student Marks")
print("2. Display All Students and Marks")
print("3. Find Student with Highest Marks")
print("4. Find Student with Lowest Marks")
print("5. Calculate Average Marks")
print("6. Exit")
7. Python program that calculates the following from a given text file:
1) Character count
2) Word count
3) Line count
4) The number of times a specific word is repeated
5) Word frequencies.
Input/Output Example
def calculate_counts(filename):
try:
with open(filename, 'r') as file:
text = file.read()
# 1) Character count
char_count = len(text)
# 2) Word count
words = text.split()
word_count = len(words)
# 3) Line count
file.seek(0)
lines = file.readlines()
line_count = len(lines)
# 5) Word frequencies
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
print("Word Frequencies:")
for word, count in word_counts.items():
print(f"{word}: {count}")
except FileNotFoundError:
print("The file was not found. Please check the filename and try again.")
except Exception as e:
print(f"An error occurred: {e}")