Set for dictionary python

Iterate through Dictionary with multiple values in Python

In this Python tutorial, we will study how to iterate through a dictionary in Python using some examples in Python. Moreover, we will also cover multiple ways to Iterating through multiple values for one dictionary and learn to loop through a dictionary of dataframes in Python.

Iterating Through a Python Dictionary with Multiple Values

In some scenarios, we might want to have multiple values associated with a single key. This can be achieved by having the values as a list, tuple, or another dictionary. So, let’s learn to iterate through a Python Dictionary with Multiple Values.

Using for loop with .items() in Python

Iterating over a dictionary in Python is straightforward using a for loop. If the dictionary has multiple values per key, the process is slightly different but still simple. Let’s take a look at how we can do this.

book_dict = < "John": ["1984", "Brave New World", "Fahrenheit 451"], "Emma": ["Pride and Prejudice", "Emma", "Persuasion"], "Paul": ["Dune", "Foundation", "Neuromancer"] >for name, books in book_dict.items(): print(f"'s favorite books are:") for book in books: print(f"- ") print() 

For instance, we can have a Python dictionary where the key is a person’s name, and the value is a list of their favorite books.

  1. book_dict.items() is used to return pairs of keys and values from the Python dictionary.
  2. for name, books in book_dict.items(): iterates over these pairs. The name variable gets the key, and the books variable gets the value (which is a list in this case).
  3. for book in books: is another for loop nested within the first one. This loop iterates over each book in the list of books.
  4. print(f»- «) prints each book.
Читайте также:  Модуль graph python поляков

Iterate through Dictionary with multiple values in Python

Using List Comprehension in Python

Now, we’ll use a Python dictionary representing countries and their corresponding currencies. And, we can use a Python list comprehension to generate a list of statements about each country.

currency_dict = < "USA": ["Dollar"], "Japan": ["Yen"], "UK": ["Pound"], "India": ["Rupee"] >[print(f"The currency of is .") for key, values in currency_dict.items()] 

Here, we use a Python dictionary currency_dict that contains countries as keys and their corresponding currencies as values. Using a list comprehension, we generate and print a list of sentences stating the currency of each country.

Iterate through Dictionary with multiple values in Python Example

Using Python Dictionary .keys() and .get()

The keys() method returns a view object that displays a list of all the keys in the Python dictionary. The get() method returns the value for the given key, if present in the Python dictionary.

Let’s consider a Python dictionary representing students and their corresponding scores in different subjects.

student_scores = < "John": [85, 92, 78], "Emma": [91, 88, 95], "Paul": [82, 87, 93] >for key in student_scores.keys(): values = student_scores.get(key) print(f"'s scores are:") for value in values: print(f"- ") print() 

In this example, we have a Python dictionary student_scores that stores students’ names as keys and their corresponding scores in different subjects as values. We use the Python keys() method to iterate over the keys (students) and the get() method to retrieve the values (scores). Then, we print the scores for each student.

Iterating Through a Python Dictionary with Multiple Values

Using Dictionary Unpacking (**) in Python

This is a more advanced method that involves creating a new Python dictionary by merging the original Python dictionary with a second dictionary that maps the keys to formatted strings.

We’ll use a Python dictionary representing people and their favorite hobbies.

hobbies_dict = < "Alice": ["Reading", "Swimming", "Cooking"], "Bob": ["Fishing", "Hiking", "Painting"], "Charlie": ["Skiing", "Traveling", "Gardening"] >for key, value in <**hobbies_dict>.items(): print(f"'s hobbies are:") for v in value: print(f"- ") print() 

This example uses a Python dictionary hobbies_dict that stores people’s names as keys and their favorite hobbies as values. We use the double asterisk () to unpack the Python dictionary and iterate over its keys (names) and values (hobbies), then print the hobbies for each person.

Iterating Through a Python Dictionary with Multiple Values Example

Using Python Lambdas and Map

We can use lambdas (anonymous functions) and the map() function to achieve the same result. This approach can be beneficial if you’re working with large Python dictionaries and you want to use the speed advantages offered by map() .

Finally, let’s consider a dictionary representing pets and their favorite foods.

pet_food_dict = < "Dog": ["Bone", "Meat", "Dog food"], "Cat": ["Fish", "Cat food", "Milk"], "Parrot": ["Seeds", "Fruits", "Nuts"] >list(map(lambda kv: print(f"A likes ."), pet_food_dict.items())) 

In the final example, we have a Python dictionary pet_food_dict that contains types of pets as keys and their favorite foods as values. We use a lambda function and the map() function to generate and print a Python list of sentences stating what each type of pet likes to eat.

Loop through dictionary of dataframes in Python

Loop through dictionary of dataframes in Python

Let’s consider an example using the pandas library in Python. Suppose we have a Python dictionary representing a dataframe, where each key is a column name and its corresponding value is a list representing the data in that column.

We will use a simple US demographic data set for this purpose.

import pandas as pd # Define a dictionary data_dict = < "State": ["California", "Texas", "New York", "Florida", "Illinois"], "Population": [39538223, 29145505, 20215751, 21538187, 12822739], "Area": [163696, 268596, 54555, 65757, 57914] # In square miles ># Convert dictionary to dataframe df = pd.DataFrame(data_dict) for index, row in df.iterrows(): print(f"State: , Population: , Area: ") 

In this dictionary, each key has a list of values. The keys are “State”, “Population”, and “Area”. We can now convert this dictionary to a pandas dataframe.

Now, to iterate through this dataframe, we can use the iterrows() function in pandas. This function returns an iterator yielding index and row data for each row, which is a bit like a Python dictionary where keys are column names.

  1. df.iterrows() is used to get an iterator yielding index and row data for each row.
  2. for index, row in df.iterrows(): iterates over these pairs. The index variable gets the index, and the row variable gets the row data (which behaves like a dictionary here).
  3. print(f»State: , Population: , Area: «) prints the data for each state. Since row behaves like a dictionary, we can access the data using column names as keys.

Loop through dictionary of dataframes in Python Example

Conclusion

Python dictionaries are a powerful data structure that allows you to store key-value pairs. When each key has multiple values associated with it, you can store these values in a data structure such as a list, tuple, or another dictionary. You can then use multiple ways to iterate through each key-value pair and each value in the list associated with each key.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью