Lists to Dictionary

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, a dictionary is a collection of key-value pairs. Sometimes, we may have two separate lists, one containing the keys and the other containing the values, and we want to combine them into a dictionary. In this challenge, you will write a function that takes two lists as input and returns a dictionary where the elements of the first list serve as the keys and the elements of the second list serve as the values.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13731{{"`Lists to Dictionary`"}} python/variables_data_types -.-> lab-13731{{"`Lists to Dictionary`"}} python/lists -.-> lab-13731{{"`Lists to Dictionary`"}} python/tuples -.-> lab-13731{{"`Lists to Dictionary`"}} python/dictionaries -.-> lab-13731{{"`Lists to Dictionary`"}} python/function_definition -.-> lab-13731{{"`Lists to Dictionary`"}} python/data_collections -.-> lab-13731{{"`Lists to Dictionary`"}} python/build_in_functions -.-> lab-13731{{"`Lists to Dictionary`"}} end

Lists to Dictionary

Write a function to_dictionary(keys, values) that takes two lists as input and returns a dictionary where the elements of the first list serve as the keys and the elements of the second list serve as the values. The function should use zip() in combination with dict() to combine the values of the two lists into a dictionary. The function should return None if the length of the two lists is not equal.

def to_dictionary(keys, values):
  return dict(zip(keys, values))
to_dictionary(['a', 'b'], [1, 2]) ## { a: 1, b: 2 }

Summary

In this challenge, you have learned how to combine two lists into a dictionary using zip() and dict(). You have also learned how to handle the case where the length of the two lists is not equal.

Other Python Tutorials you may like