简体   繁体   中英

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM