How can i get values from 2 lists and put them into a dictionary in python

Question:

I have 2 lists

list1 = ["ben", "tim", "john", "wally"]
list2 = [18,12,34,55]

the output im looking for is this

[{'Name': 'ben', 'Age': 18, 'Name': 'tim', 'Age': 12, 'Name': 'john', 'Age': 34, 'Name': 'wally', 'Age': 55}]
Asked By: CodingOwl

||

Answers:

use a list comprehension to combine the two lists into a list of dictionaries like this:

list1 = ["ben", "tim", "john", "wally"]
list2 = [18,12,34,55]
result = [{'Name': name, 'Age': age} for name, age in zip(list1, list2)]
result

will output this:

[{'Name': 'ben', 'Age': 18},
 {'Name': 'tim', 'Age': 12},
 {'Name': 'john', 'Age': 34},
 {'Name': 'wally', 'Age': 55}]
Answered By: Phoenix

To create a dictionary from two lists, you can use the zip() function to iterate over the lists and create key-value pairs. Then, you can use the dict() function to create a dictionary from the list of key-value pairs.

Here’s an example of how you can do this:

list1 = ["ben", "tim", "john", "wally"]
list2 = [18, 12, 34, 55]

# Create a list of tuples, where each tuple is a key-value pair
pairs = list(zip(list1, list2))

# Create a dictionary from the list of tuples
dictionary = dict(pairs)

print(dictionary)

This will output the following dictionary:

{'ben': 18, 'tim': 12, 'john': 34, 'wally': 55}

If you want to create a list of dictionaries, where each dictionary contains a single key-value pair, you can use a list comprehension to iterate over the lists and create the dictionaries.

list1 = ["ben", "tim", "john", "wally"]
list2 = [18, 12, 34, 55]

# Create a list of dictionaries, where each dictionary is a single key-value pair
dictionaries = [{"Name": name, "Age": age} for name, age in zip(list1, list2)]

print(dictionaries)

This will output the following list of dictionaries:

[{'Name': 'ben', 'Age': 18}, {'Name': 'tim', 'Age': 12}, {'Name': 'john', 'Age': 34}, {'Name': 'wally', 'Age': 55}]

I hope this helps! Let me know if you have any questions.

Answered By: Ahmad Siddiqui
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.