""" How to convert 2 lists into a dictionary in python """
# list used for keys in dictionary
students = ["Angela", "James", "Lily"]
# list of values
scores = [56, 76, 98]
# convert lists to dictionary
student_scores = dict(zip(students, scores))
# print the dictionary
print(student_scores)
""" result should be
student_scores: -{
Angela: 56,
James: 76,
Lily: 98
},
"""
l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]
d = {k: v for x in l for k, v in x.items()}
print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
column_names = ['id', 'color', 'style']
column_values = [1, 'red', 'bold']
# Convert two lists into a dictionary with zip and the dict constructor
name_to_value_dict = dict(zip(column_names, column_values))
# Convert two lists into a dictionary with a dictionary comprehension
name_to_value_dict = {key:value for key, value in zip(column_names, column_values)}
# Convert two lists into a dictionary with a loop
name_value_tuples = zip(column_names, column_values)
name_to_value_dict = {}
for key, value in name_value_tuples:
if key in name_to_value_dict:
pass # Insert logic for handling duplicate keys
else:
name_to_value_dict[key] = value