Translate

Saturday 9 March 2024

Iterating over Dictionaries in python 19

 Iterating over Dictionaries in python

Understanding Dictionaries

  • Dictionaries are unordered collections of key-value pairs.

  • Keys must be unique and immutable (e.g., strings, numbers, tuples).

  • Values can be of any data type, including duplicates.

Methods for Iterating over Dictionaries

  1. Iterating over Keys:

  • Directly in a for loop: This is the simplest way to loop through a dictionary's keys.
    Python
    my_dict = {"name": "Alice", "city": "New York", "age": 30}
    for key in my_dict:
        print(key, my_dict[key])

  1. Using the .keys() method: This method returns a view object containing the dictionary's keys.
    Python
    for key in my_dict.keys():
        print(key, my_dict[key])

  2. Iterating over Values:

  • Using the .values() method: This method returns a view object containing the dictionary's values.
    Python
    for value in my_dict.values():
        print(value)

  1. Iterating over Key-Value Pairs:

  • Using the .items() method: This method returns a view object of key-value pairs as tuples. It's the most common way to access both keys and values together.

Python
for key, value in my_dict.items():
    print(key, value)

Choosing the Right Method

  • If you only need to work with the keys, directly iterating over the dictionary or using .keys() is efficient.

  • If you only need the values, use .values().

  • If you need to manipulate both keys and values during iteration, use .items().

Important Note: In Python 2, the .keys(), .values(), and .items() methods return lists. In Python 3, they return view objects, which are more memory-efficient for iteration.

Iterating over Dictionaries example programs:

Example 1: Product Price Catalog


Python


product_prices = {
    "apple": 1.50,
    "banana": 0.75,
    "orange": 1.25,
    "strawberry": 2.00
}

# Print each product and its price
for product, price in product_prices.items():
    print(f"The price of {product} is ${price:.2f}")

Example 2: Student Grades


Python


grades = {
    "Alice": [92, 85, 76],
    "Bob": [88, 90, 95],
    "Charlie": [70, 65, 81]
}

# Calculate and print average grade for each student
for student, scores in grades.items():
    average_grade = sum(scores) / len(scores)
    print(f"{student}'s average grade: {average_grade:.1f}")

Example 3: Phone Book


Python


phone_book = {
    "Alice": "123-456-7890",
    "Bob": "987-654-3210",
    "Eve": "555-1212"
}

#  Search for a contact by name
search_name = input("Enter the name to search: ")

if search_name in phone_book:
    print(f"{search_name}'s phone number is {phone_book[search_name]}")
else:
    print(f"{search_name} not found in the phone book.")

Tips:

  • .items() is the most common method when you need both keys and values during iteration.

  • Iterating directly over the dictionary primarily gives you the keys. Use this when you only need the keys or when you can directly get the values using square bracket notation (dict[key]).

  • .values() is used when you only care about the values and don't need the keys during the iteration.



Dictionaries with Data Visualization  example pro...

Example 1: Population Distribution by Country


Python


import matplotlib.pyplot as plt

population_data = {
    "China": 1400000000,
    "India": 1350000000,
    "United States": 330000000,
    "Indonesia": 270000000,
    "Brazil": 210000000
}

# Extract countries and population values
countries = list(population_data.keys())
population = list(population_data.values())

# Sort the data together (descending order by population)
data = zip(population, countries)
sorted_data = sorted(data, reverse=True)

population, countries = zip(*sorted_data)

# Create a horizontal bar chart
plt.barh(countries, population)
plt.xlabel("Population")
plt.ylabel("Country")
plt.title("Population Distribution by Country")
plt.show()

Example 2: Website Traffic by Source


Python


import matplotlib.pyplot as plt

traffic_sources = {
    "Direct": 3000,
    "Organic Search": 5500,
    "Social Media": 1600,
    "Referral": 800,
    "Email": 1200
}

# Prepare data for a pie chart
sources = list(traffic_sources.keys())
traffic_values = list(traffic_sources.values())

# Create a pie chart
plt.pie(traffic_values, labels=sources, autopct="%1.1f%%")
plt.title("Website Traffic Sources")
plt.show()

Let's Break Down the Key Points:

  • Dictionary Data: Your dictionary holds the data you want to visualize. The keys often become labels, and the values represent the numerical data to plot.

  • Data Preparation: Sometimes you might need to sort or extract the data into separate lists (as in the first example) to suit the chosen chart type.

  • Chart Selection: Choose the visualization that best represents your data:

  • plt.bar() or plt.barh() for bar charts (categorical comparisons)

  • plt.pie() for pie charts (part-to-whole relationships)

  • plt.plot() for line charts (trends over time)

  • Customization: Always add labels and titles for clarity. Explore Matplotlib's options for further customization of colors, legends, etc.

Important: Ensure you have Matplotlib installed (pip install matplotlib).



Example: Visualizing Product Sales by Category


Python


import matplotlib.pyplot as plt

sales_data = {
    "Electronics": 5000,
    "Clothing": 2500,
    "Home Goods": 3000,
    "Books": 1000,
    "Other": 750
}

# Filter categories with sales above a threshold
threshold = 1500
filtered_data = {}

for category, sales in sales_data.items():
    if sales > threshold:
        filtered_data[category] = sales

# Prepare data for plotting
categories = list(filtered_data.keys())
sales_values = list(filtered_data.values())

# Create a bar chart
plt.bar(categories, sales_values)
plt.xlabel("Product Categories")
plt.ylabel("Sales ($)")
plt.title("Sales by Category (Above $1500 Threshold)")
plt.show()

Explanation:

  1. Data: We define a sales_data dictionary representing product sales across different categories.

  2. Filtering: We set a threshold and use a for loop with a conditional statement to create a new dictionary filtered_data, containing only categories exceeding the sales threshold.

  3. Data Preparation: We extract the categories and their corresponding sales values into separate lists for plotting.

  4. Visualization: We use matplotlib.pyplot.bar() to create a bar chart visualizing the filtered sales data.

  5. Customization: We add labels and a title to the chart for clarity.

Enhancements:

  • Sorting: Sort the bars by value for better visual representation.

  • Pie Chart: Instead of a bar chart, try plt.pie() for a pie chart visualization.

  • Error Handling: Consider handling cases with no data exceeding the threshold.

Important Note: Make sure you have the 'matplotlib' library installed (pip install matplotlib).

Let me know if you'd like to explore the following:

  • More complex data filtering conditions

  • Different chart types (line charts, scatter plots, etc.)

  • Visualization of nested dictionaries





19 Iterating over Dictionaries

No comments:

Post a Comment

Note: only a member of this blog may post a comment.