Python - Value Dictionary from Record List

Python - Value Dictionary from Record List

If you want to generate a dictionary from a list of records (typically tuples or lists), this tutorial can guide you through the process.

Objective:

Given a list of records, where each record contains key-value pairs, create a dictionary using these pairs.

Example:

Suppose we have a list of students' records in the form of tuples where each tuple contains the student's ID and their grade:

records = [(101, "A"), (102, "B"), (103, "A+")] 

We want to transform it into a dictionary where student IDs are the keys and grades are the values:

{ 101: "A", 102: "B", 103: "A+" } 

Steps:

  1. Initialize an Empty Dictionary: Begin with an empty dictionary to store the result.

  2. Iterate Through the Records: Loop through each record in the list of records.

  3. Add Key-Value Pairs to Dictionary: For each record, use the first element as the key and the second element as the value.

Code:

Here's an implementation of the described steps:

def dict_from_records(records): # Initialize an empty dictionary result = {} # Iterate through each record for record in records: key, value = record result[key] = value return result # Test the function records = [(101, "A"), (102, "B"), (103, "A+")] print(dict_from_records(records)) # Output: {101: 'A', 102: 'B', 103: 'A+'} 

Explanation:

  • We initialize an empty dictionary called result.

  • For each record in the list, we unpack its elements into key and value.

  • We then assign the value to the corresponding key in the result dictionary.

Alternate Method (Using Dictionary Comprehension):

Python also supports dictionary comprehensions, which provide a concise way to create dictionaries:

def dict_from_records(records): return {key: value for key, value in records} # Test the function records = [(101, "A"), (102, "B"), (103, "A+")] print(dict_from_records(records)) # Output: {101: 'A', 102: 'B', 103: 'A+'} 

Conclusion:

Creating dictionaries from lists of records (like tuples or lists) is a common task in Python. With the steps and techniques presented in this tutorial, you can efficiently transform such records into dictionaries.


More Tags

except iconbutton string-length parsing distinct-values laravel-5.1 hidden-field epmd rvm self-extracting

More Programming Guides

Other Guides

More Programming Examples