Create a Dictionary of Names and Ages from a List of Tuples in Python

This tutorial provides a Python function to transform a list of tuples containing person-age information into a dictionary.

Here's the code:pythondef create_age_dictionary(persons): 'This function takes a list of tuples, each containing a person's name and age, and returns a dictionary with names as keys and ages as values.' age_dict = {} for person in persons: name, age = person age_dict[name] = age return age_dict

Example inputpersons = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

Call the function and print the resultage_dictionary = create_age_dictionary(persons)print(age_dictionary)

Output:

{'Alice': 25, 'Bob': 30, 'Charlie': 35}

Explanation:

  1. create_age_dictionary(persons) function: - Takes a list of tuples (persons) as input. - Initializes an empty dictionary age_dict. - Iterates through each tuple (person) in the persons list. - Unpacks each tuple into name and age variables. - Assigns the name as the key and age as the value in the age_dict dictionary. - Returns the populated age_dict.

  2. Example Usage: - Defines a list of tuples persons with sample data. - Calls the create_age_dictionary function with persons as input. - Stores the returned dictionary in age_dictionary. - Prints the age_dictionary.

This example demonstrates a simple yet effective way to convert data structures in Python, making it easier to work with and access information. This pattern is common in data manipulation and processing tasks.

Python Function to Create a Dictionary of Names and Ages from a List of Tuples

原文地址: https://www.cveoy.top/t/topic/IPc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录