key-value pair format and mutable data-structure
Value can be any type such as list, tuple, integer, etc.
Creating an empty Dictionary using Dict methods
Accessing the dictionary values
print("Name : %s" %Employee["Name"])
Adding dictionary values
Dict[0] = 'Peter'||Dict[key]
Dict['Emp_ages'] = 20, 33, 24
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Deleting elements using del keyword
del Employee["Name"]
Deleting elements using pop() method
Iterating Dictionary using for loop
for loop to print all the values of the dictionary
print(Employee[x])
for loop to print the values of the dictionary by using values()
for x in Employee.values():
for loop to print the items of the dictionary by using items()
for x in Employee.items():
o/p=('Name', 'John')
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:).The syntax to define the dictionary is given below.
Syntax:
Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
Let's see an example to create a dictionary and print its content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {} is used to create empty dictionary.
Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Java', 2: 'T', 3: 'Point'}
Dictionary with each item as a pair:
{1: 'Devansh', 2: 'Sharma'}
Accessing the dictionary values
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing.
Adding dictionary values
The dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value.
Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
Example - 1:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Example - 2:
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}
Deleting elements using del keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined
The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted.
Using pop() method
The pop() method accepts the key as an argument and remove the associated value. Consider the following example.
# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
Output:
{1: 'JavaTpoint', 2: 'Peter'}
Python also provides a built-in methods popitem() and clear() method for remove elements from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method removes all elements to the whole dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x)
Output:
Name
Age
salary
Company
Example 2
for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(Employee[x])
Output:
John
29
25000
GOOGLE
Example - 3
for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.values():
print(x)
Output:
John
29
25000
GOOGLE
Example 4
for loop to print the items of the dictionary by using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.items():
print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary keys
- In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key.
Consider the following example.
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}
for x,y in Employee.items():
print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE
=========================================================
Dictionary Question
- Create an empty dictionary and add key-value pairs for the names and ages of three people.
- Add a new key-value pair to an existing dictionary representing a student's grade in a subject.
- Given a dictionary of items and their prices, calculate the total cost of a shopping cart.
- Create a dictionary of words and their meanings, and look up the meaning of a specific word.
- Iterate through a dictionary of countries and their capitals and print them out.
- Write a function to merge two dictionaries into one.
- Count the occurrences of each character in a given string and store them in a dictionary.
- Remove a key-value pair from a dictionary and print the updated dictionary.
- Given a list of numbers, create a dictionary with the numbers as keys and their squares as values.
- Create a dictionary that represents a contact list and allows searching for contacts by name.
- Write a function to invert the keys and values of a dictionary.
- Remove duplicate values from a dictionary while keeping the original order.
- Calculate the average score from a dictionary containing student names and their scores.
- Create a dictionary to store information about books (title, author, year), and allow searching by title.
- Write a function to find the key associated with the maximum value in a dictionary.
- Create a dictionary representing a deck of cards and shuffle it randomly.
- Group a list of words by their lengths and store them in a dictionary.
- Create a dictionary to store information about movies (title, director, genre), and allow adding new movies.
- Write a function to find the common keys between two dictionaries.
- Create a dictionary to store words and their synonyms, and allow searching for synonyms.
- Sort a dictionary by its values in ascending order.
- Write a function to flatten a nested dictionary into a single dictionary.
- Create a dictionary of fruits and their quantities. Update the quantity of a specific fruit.
- Check if a key exists in a dictionary and print a corresponding message.
- Calculate the average length of values in a dictionary containing lists of strings.
- Create a dictionary representing a simple phonebook and allow adding, updating, and deleting contacts.
- Find the key associated with the minimum value in a dictionary using a function.
- Create a dictionary of song ratings and titles. Print the titles of the top-rated songs.
- Merge multiple dictionaries into a new dictionary.
- Create a dictionary to store information about cities (name, population, country), and find the most populous city .
# Task 1: Create an empty dictionary and add key-value pairs for the names and ages of three people.
people_dict = {}
people_dict["Alice"] = 25
people_dict["Bob"] = 30
people_dict["Charlie"] = 22
print("Task 1 - Dictionary of People:", people_dict)
# Task 2: Add a new key-value pair to an existing dictionary representing a student's grade in a subject.
student_dict = {"Alice": 90, "Bob": 85, "Charlie": 78}
student_dict["David"] = 92
print("Task 2 - Updated Student Dictionary:", student_dict)
# Task 3: Given a dictionary of items and their prices, calculate the total cost of a shopping cart.
shopping_cart = {"apple": 1.0, "banana": 0.5, "cherry": 1.5, "date": 0.75}
cart_items = ["apple", "banana", "cherry"]
total_cost = sum(shopping_cart[item] for item in cart_items)
print("Task 3 - Total Cost of Shopping Cart:", total_cost)
# Task 4: Create a dictionary of words and their meanings, and look up the meaning of a specific word.
dictionary = {
"apple": "a round fruit with red or green skin and white flesh",
"banana": "a long curved fruit with yellow skin",
"cherry": "a small, round, red or black fruit with a stone inside",
}
word_to_lookup = "banana"
meaning = dictionary.get(word_to_lookup, "Word not found in dictionary")
print("Task 4 - Meaning of '{}':".format(word_to_lookup), meaning)
# Task 5: Iterate through a dictionary of countries and their capitals and print them out.
countries_dict = {
"USA": "Washington D.C.",
"France": "Paris",
"Germany": "Berlin",
"Japan": "Tokyo",
}
print("Task 5 - Countries and Capitals:")
for country, capital in countries_dict.items():
print("{} - {}".format(country, capital))
# Task 6: Write a function to merge two dictionaries into one.
def merge_dicts(dict1, dict2):
return {**dict1, **dict2}
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = merge_dicts(dict1, dict2)
print("Task 6 - Merged Dictionary:", merged_dict)
# Task 7: Count the occurrences of each character in a given string and store them in a dictionary.
def count_characters(input_string):
char_count = {}
for char in input_string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
text = "hello world"
char_counts = count_characters(text)
print("Task 7 - Character Counts:", char_counts)
# Task 8: Remove a key-value pair from a dictionary and print the updated dictionary.
contact_dict = {
"Alice": "alice@example.com",
"Bob": "bob@example.com",
"Charlie": "charlie@example.com",
}
key_to_remove = "Charlie"
if key_to_remove in contact_dict:
del contact_dict[key_to_remove]
print("Task 8 - Updated Contact Dictionary:", contact_dict)
# Task 9: Given a list of numbers, create a dictionary with the numbers as keys and their squares as values.
numbers_list = [1, 2, 3, 4, 5]
squares_dict = {num: num ** 2 for num in numbers_list}
print("Task 9 - Dictionary of Numbers and Their Squares:", squares_dict)
# Task 10: Create a dictionary that represents a contact list and allows searching for contacts by name.
contacts_dict = {
"Alice": "alice@example.com",
"Bob": "bob@example.com",
"Charlie": "charlie@example.com",
}
name_to_lookup = "Bob"
contact_email = contacts_dict.get(name_to_lookup, "Contact not found")
print("Task 10 - Email for '{}':".format(name_to_lookup), contact_email)
# Task 11: Write a function to invert the keys and values of a dictionary.
def invert_dict(input_dict):
return {value: key for key, value in input_dict.items()}
original_dict = {"a": 1, "b": 2, "c": 3}
inverted_dict = invert_dict(original_dict)
print("Task 11 - Inverted Dictionary:", inverted_dict)
# Task 12: Remove duplicate values from a dictionary while keeping the original order.
from collections import OrderedDict
def remove_duplicates_from_dict(input_dict):
return dict(OrderedDict.fromkeys(input_dict))
duplicates_dict = {"a": 1, "b": 2, "c": 1, "d": 3, "e": 2}
unique_dict = remove_duplicates_from_dict(duplicates_dict)
print("Task 12 - Dictionary with Duplicate Values Removed:", unique_dict)
# Task 13: Calculate the average score from a dictionary containing student names and their scores.
scores_dict = {"Alice": 90, "Bob": 85, "Charlie": 78}
average_score = sum(scores_dict.values()) / len(scores_dict)
print("Task 13 - Average Score of Students:", average_score)
# Task 14: Create a dictionary to store information about books (title, author, year), and allow searching by title.
books_dict = {
"Book1": {"author": "Author1", "year": 2021},
"Book2": {"author": "Author2", "year": 2020},
"Book3": {"author": "Author3", "year": 2019},
}
title_to_lookup = "Book2"
book_info = books_dict.get(title_to_lookup, "Book not found")
print("Task 14 - Information for '{}':".format(title_to_lookup), book_info)
# Task 15: Write a function to find the key associated with the maximum value in a dictionary.
def key_with_max_value(input_dict):
return max(input_dict, key=input_dict.get)
scores_dict = {"Alice": 90, "Bob": 85, "Charlie": 78}
key_max_score = key_with_max_value(scores_dict)
print("Task 15 - Student with Maximum Score:", key_max_score)
Output
Task 1 - Dictionary of People: {'Alice': 25, 'Bob': 30, 'Charlie': 22}
Task 2 - Updated Student Dictionary: {'Alice': 90, 'Bob': 85, 'Charlie': 78, 'David': 92}
Task 3 - Total Cost of Shopping Cart: 3.0
Task 4 - Meaning of 'banana': a long curved fruit with yellow skin
Task 5 - Countries and Capitals:
USA - Washington D.C.
France - Paris
Germany - Berlin
Japan - Tokyo
Task 6 - Merged Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Task 7 - Character Counts: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Task 8 - Updated Contact Dictionary: {'Alice': 'alice@example.com', 'Bob': 'bob@example.com'}
Task 9 - Dictionary of Numbers and Their Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Task 10 - Email for 'Bob': bob@example.com
Task 11 - Inverted Dictionary: {1: 'a', 2: 'b', 3: 'c'}
Task 12 - Dictionary with Duplicate Values Removed: {'a': 1, 'b': 2, 'd': 3}
Task 13 - Average Score of Students: 84.33333333333333
Task 14 - Information for 'Book2': {'author': 'Author2', 'year': 2020}
Task 15 - Student with Maximum Score: Alice
import random
# Task 1: Create a dictionary representing a deck of cards and shuffle it randomly.
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
deck_of_cards = [{"Suit": suit, "Value": value} for suit in suits for value in values]
random.shuffle(deck_of_cards)
print("Task 1 - Shuffled Deck of Cards (Partial Output):", deck_of_cards[:5])
# Task 2: Group a list of words by their lengths and store them in a dictionary.
words_list = ["apple", "banana", "cherry", "date", "elderberry"]
word_length_dict = {}
for word in words_list:
length = len(word)
if length in word_length_dict:
word_length_dict[length].append(word)
else:
word_length_dict[length] = [word]
print("Task 2 - Words Grouped by Length:", word_length_dict)
# Task 3: Create a dictionary to store information about movies (title, director, genre), and allow adding new movies.
movies_dict = {
"Movie1": {"director": "Director1", "genre": "Genre1"},
"Movie2": {"director": "Director2", "genre": "Genre2"},
}
new_movie = {"director": "Director3", "genre": "Genre3"}
movies_dict["Movie3"] = new_movie
print("Task 3 - Updated Movies Dictionary:", movies_dict)
# Task 4: Write a function to find the common keys between two dictionaries.
def find_common_keys(dict1, dict2):
return set(dict1.keys()) & set(dict2.keys())
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"b": 4, "c": 5, "d": 6}
common_keys = find_common_keys(dict1, dict2)
print("Task 4 - Common Keys Between dict1 and dict2:", common_keys)
# Task 5: Create a dictionary to store words and their synonyms, and allow searching for synonyms.
synonyms_dict = {
"happy": ["joyful", "content", "cheerful"],
"sad": ["unhappy", "melancholy", "depressed"],
}
word_to_lookup = "happy"
synonyms = synonyms_dict.get(word_to_lookup, "Synonyms not found")
print("Task 5 - Synonyms for '{}':".format(word_to_lookup), synonyms)
# Task 6: Sort a dictionary by its values in ascending order.
scores_dict = {"Alice": 90, "Bob": 85, "Charlie": 78}
sorted_scores = dict(sorted(scores_dict.items(), key=lambda item: item[1]))
print("Task 6 - Sorted Scores Dictionary:", sorted_scores)
# Task 7: Write a function to flatten a nested dictionary into a single dictionary.
def flatten_dict(input_dict, parent_key='', sep='_'):
flattened_dict = {}
for key, value in input_dict.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
flattened_dict.update(flatten_dict(value, new_key, sep=sep))
else:
flattened_dict[new_key] = value
return flattened_dict
nested_dict = {
'a': 1,
'b': {'c': 2, 'd': {'e': 3, 'f': 4}},
'g': 5
}
flattened_dict = flatten_dict(nested_dict)
print("Task 7 - Flattened Dictionary:", flattened_dict)
# Task 8: Create a dictionary of fruits and their quantities. Update the quantity of a specific fruit.
fruit_quantities = {"apple": 10, "banana": 15, "cherry": 5}
fruit_to_update = "banana"
new_quantity = 20
if fruit_to_update in fruit_quantities:
fruit_quantities[fruit_to_update] = new_quantity
print("Task 8 - Updated Fruit Quantities:", fruit_quantities)
# Task 9: Check if a key exists in a dictionary and print a corresponding message.
contact_dict = {
"Alice": "alice@example.com",
"Bob": "bob@example.com",
"Charlie": "charlie@example.com",
}
key_to_check = "David"
if key_to_check in contact_dict:
print("Task 9 - Key '{}' exists in the dictionary.".format(key_to_check))
else:
print("Task 9 - Key '{}' does not exist in the dictionary.".format(key_to_check))
# Task 10: Calculate the average length of values in a dictionary containing lists of strings.
list_dict = {"fruits": ["apple", "banana", "cherry"], "colors": ["red", "green", "blue"]}
average_length = sum(len(value) for values in list_dict.values() for value in values) / len(list_dict)
print("Task 10 - Average Length of Values:", average_length)
# Task 11: Create a dictionary representing a simple phonebook and allow adding, updating, and deleting contacts.
phonebook = {"Alice": "123-456-7890", "Bob": "987-654-3210"}
# Adding a contact
phonebook["Charlie"] = "555-555-5555"
# Updating a contact
phonebook["Bob"] = "999-999-9999"
# Deleting a contact
if "Alice" in phonebook:
del phonebook["Alice"]
print("Task 11 - Updated Phonebook:", phonebook)
# Task 12: Find the key associated with the minimum value in a dictionary using a function.
def key_with_min_value(input_dict):
return min(input_dict, key=input_dict.get)
scores_dict = {"Alice": 90, "Bob": 85, "Charlie": 78}
key_min_score = key_with_min_value(scores_dict)
print("Task 12 - Student with Minimum Score:", key_min_score)
# Task 13 (continued): Create a dictionary of song ratings and titles. Print the titles of the top-rated songs.
song_ratings = {"Song1": 5, "Song2": 4, "Song3": 5, "Song4": 3, "Song5": 4}
top_rated_songs = [title for title, rating in song_ratings.items() if rating == 5]
print("Task 13 - Top-Rated Songs:", top_rated_songs)
# Task 14: Merge multiple dictionaries into a new dictionary.
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict3 = {"e": 5}
merged_dict = {**dict1, **dict2, **dict3}
print("Task 14 - Merged Dictionary:", merged_dict)
# Task 15: Create a dictionary to store information about cities (name, population, country), and find the most populous city.
cities_dict = {
"City1": {"population": 1000000, "country": "Country1"},
"City2": {"population": 1500000, "country": "Country2"},
"City3": {"population": 800000, "country": "Country1"},
}
most_populous_city = max(cities_dict, key=lambda city: cities_dict[city]["population"])
print("Task 15 - Most Populous City:", most_populous_city)
output
Task 1 - Shuffled Deck of Cards (Partial Output): [{'Suit': 'Clubs', 'Value': '6'}, {'Suit': 'Spades', 'Value': '9'}, {'Suit': 'Spades', 'Value': '2'}, {'Suit': 'Diamonds', 'Value': 'King'}, {'Suit': 'Diamonds', 'Value': '7'}]
Task 2 - Words Grouped by Length: {5: ['apple', 'cherry'], 6: ['banana'], 4: ['date'], 11: ['elderberry']}
Task 3 - Updated Movies Dictionary: {'Movie1': {'director': 'Director1', 'genre': 'Genre1'}, 'Movie2': {'director': 'Director2', 'genre': 'Genre2'}, 'Movie3': {'director': 'Director3', 'genre': 'Genre3'}}
Task 4 - Common Keys Between dict1 and dict2: {'b', 'c'}
Task 5 - Synonyms for 'happy': ['joyful', 'content', 'cheerful']
Task 6 - Sorted Scores Dictionary: {'Charlie': 78, 'Bob': 85, 'Alice': 90}
Task 7 - Flattened Dictionary: {'a': 1, 'b_c': 2, 'b_d_e': 3, 'b_d_f': 4, 'g': 5}
Task 8 - Updated Fruit Quantities: {'apple': 10, 'banana': 20, 'cherry': 5}
Task 9 - Key 'David' does not exist in the dictionary.
Task 10 - Average Length of Values: 5.0
Task 11 - Updated Phonebook: {'Bob': '999-999-9999', 'Charlie': '555-555-5555'}
Task 12 - Student with Minimum Score: Charlie
Task 13 - Top-Rated Songs: ['Song1', 'Song3']
Task 14 - Merged Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Task 15 - Most Populous City: City2
Good question with Dictionary
Count the occurrences of each character in a given string and store them in a dictionary.
Given a list of numbers, create a dictionary with the numbers as keys and their squares as values.
Create a dictionary representing a deck of cards and shuffle it randomly.
Group a list of words by their lengths and store them in a dictionary.
sort a dictionary by its values in ascending order.
Write a function to flatten a nested dictionary into a single dictionary.
Create a dictionary of song ratings and titles. Print the titles of the top-rated songs.
Top comments (0)