Python Function to Create a Dictionary of Names and Ages from a List of Tuples
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:
-
create_age_dictionary(persons)function: - Takes a list of tuples (persons) as input. - Initializes an empty dictionaryage_dict. - Iterates through each tuple (person) in thepersonslist. - Unpacks each tuple intonameandagevariables. - Assigns thenameas the key andageas the value in theage_dictdictionary. - Returns the populatedage_dict. -
Example Usage: - Defines a list of tuples
personswith sample data. - Calls thecreate_age_dictionaryfunction withpersonsas input. - Stores the returned dictionary inage_dictionary. - Prints theage_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.
原文地址: https://www.cveoy.top/t/topic/IPc 著作权归作者所有。请勿转载和采集!