Search code examples
pythonpython-3.xlistdictionarylist-comprehension

Create a List of Dictionaries using Comprehension


I currently have a list of strings that I am trying to create each string item into a dictionary object and store it within a list.

In attempting to create this list of dictionaries, I repeatedly create one big dictionary instead of iterating through item by item.

My code:

clothes_dict = [{clothes_list[i]: clothes_list[i + 1] for i in range(0, len(clothes_list), 2)}]

The error (All items being merged into one dictionary):

clothes_dict = {list: 1} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
 0 = {dict: 2} {'name': 'Tom', 'age': 10}, {dict: 2} {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}```

Target Output (All Items being created into separate dictionaries within the single list):

clothes_dict = {list: 3} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
 0 = {dict: 2} {'name': 'Tom', 'age': 10}
 1 = {dict: 2} {'name': 'Mark', 'age': 5}
 2 = {dict: 2} {'name': 'Pam', 'age': 7}```

I am attempting to make each entry within the list a new dictionary in the same form as the target output image.


Solution

  • clothes_dict = [{clothes_list[i]: clothes_list[i + 1]} for i in range(0, len(clothes_list), 2)]
    

    You misplaced your closing right curly brace '}' in your list comprehension and placed it at the end which meant you was performing a dictionary comprehension as opposed to a list comprehension with each item being a dictionary.