I would like to know if there is any way to get a dictionary with keys from a list of lists.
List of lists:
users = [['1043100330', 'Smith', 'John'],
['1043100331', 'Swartz', 'Francis'],
['1043100332', 'Laff', 'Michael']]
Keys:
user_keys = ['phoneNumber', 'lastName', 'firstName']
I would like to get the following:
resultado=[{'phoneNumber': '1043100330', 'lastName': 'Smith, 'firstName': 'John'},
{'phoneNumber': '1043100331', 'lastName': 'Swartz', 'firstName': 'Francis'},
{'phoneNumber': '1043100332', 'lastName': 'Laff', 'firstName': 'Michael'},
]
This is my code in Python3.6:
for user in users:
for i in users:
d = dict(zip(user_keys, i))
print(d)
But the output is:
{'phoneNumber': '1043100332', 'lastName': 'Laff', 'firstName': 'Michael'}
Thank you!
Your strategy of using
zip()
to create the dictionary was correct, but you needed to add each one of the dictionariesd
that you are creating to a list (and you had one of the nested loops left over).You can do it in one line using list comprehensions:
It is obtained like this:
Edited note: I misconveyed my idea. The point is that my answer is not intended to replace the accepted answer, but to give an alternative that can help you learn from the error and understand the solution.
Explanation
Your error is because each time this line is executed
d = dict(zip(user_keys, i))
you create a new dictionary and change the value of the variable d to the new dictionary. This causes the old dictionary to be removed since there is no variable referencing it. And what you print to d is the last dictionary you created before the for loop ended.Also, it is not necessary to do the nested for, that will make you have all the items repeated as many times as there are items in the original list (if you had a list and were adding the dictionaries to it). In your case it would be 3 times.
Think of your code as doing something equivalent to the following:
What you want to achieve is a list of dictionaries. To achieve this you first have to create the list and then add the created dictionary at the end.
Solution
You can apply the following method:
Which has a list comprehension equivalent to this: