How to make a python dictionary from two lists
Creating a Python dictionary from two lists: example: dict({'a':1,'b':2,'c':3}) # key-value pairs from lists.
Creating a Python Dictionary from Two Lists
Python dictionaries are incredibly useful data structures for storing and manipulating data. Fortunately, dictionaries can be created from two lists. To do this, you need to use thezip()
function and the dict()
function.
Let's take a look at an example. Say we have two lists, names
and ages
, that contain the names and ages of five people:
names = ["Jane", "John", "Dave", "Tom", "Sarah"]
ages = [21, 28, 32, 29, 25]
We can use the zip()
function to combine these two lists together into an object of tuples. Each tuple will contain one name and one age:
people = zip(names, ages)
print(list(people))
# Output: [('Jane', 21), ('John', 28), ('Dave', 32), ('Tom', 29), ('Sarah', 25)]
Now we can use the dict()
function to create a dictionary from this object of tuples. The names will become the keys, and the ages will become the values:
people_dict = dict(people)
print(people_dict)
# Output: {'Jane': 21, 'John': 28, 'Dave': 32, 'Tom': 29, 'Sarah': 25}
And that's it! We now have a dictionary that contains the names and ages of five people.
p