Python | Dictionary creation using list contents

Python | Dictionary creation using list contents

Creating a dictionary from lists is a common operation in Python. In this tutorial, we'll explore different ways to create dictionaries using the contents of lists.

1. Two Lists: One for Keys, One for Values

If you have two lists, one containing keys and the other containing values, you can easily convert them into a dictionary.

Example:

keys = ["a", "b", "c"] values = [1, 2, 3] 

To get:

{"a": 1, "b": 2, "c": 3} 

Code:

dictionary = dict(zip(keys, values)) print(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3} 

2. List of Tuples

If you have a list of tuples where each tuple consists of two elements - key and value, you can convert it directly into a dictionary.

Example:

pairs = [("a", 1), ("b", 2), ("c", 3)] 

To get:

{"a": 1, "b": 2, "c": 3} 

Code:

dictionary = dict(pairs) print(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3} 

3. List of Lists

If you have a list of lists, where inner lists have two elements - key and value, you can convert it into a dictionary in a manner similar to the list of tuples.

Example:

list_of_lists = [["a", 1], ["b", 2], ["c", 3]] 

To get:

{"a": 1, "b": 2, "c": 3} 

Code:

dictionary = dict(list_of_lists) print(dictionary) # Output: {'a': 1, 'b': 2, 'c': 3} 

4. List to Dictionary with Same Values

If you have a list and you want to create a dictionary where list elements become the keys and they all have a common value:

Example:

elements = ["a", "b", "c"] 

To get:

{"a": "default", "b": "default", "c": "default"} 

Code:

value = "default" dictionary = {key: value for key in elements} print(dictionary) # Output: {'a': 'default', 'b': 'default', 'c': 'default'} 

Conclusion:

Python offers flexible and concise ways to create dictionaries from lists, whether you're working with parallel lists, lists of pairs, or even single lists. Using built-in functions like dict and zip, as well as comprehensions, makes the process straightforward and efficient.


More Tags

tornado apache-beam-io commit sidekiq hibernate-entitymanager promise httppostedfilebase flask-bootstrap jsonparser purrr

More Programming Guides

Other Guides

More Programming Examples