Home > Blockchain >  Create a List of Dictionaries using Comprehension
Create a List of Dictionaries using Comprehension

Time:11-28

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: One Dictionary item full of data

Target Output (ignore data):

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.

CodePudding user response:

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.

CodePudding user response:

Your code creates a list with a single dictionary:

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

If you (for some reason) want a list of dictionaries with single entries:

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

However, it seems to me that this may be a bit of an XY problem - in what case is a list of single-entry dictionaries the required format? Why not use a list of tuples for example?

  • Related