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

Time:01-03

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}]

CodePudding user response:

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}]

CodePudding user response:

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.

  • Related