简体   繁体   中英

Turn a list of one dictionary into a list of two dictionaries using the same key

This is my code:

new_weights = [[1, 2, 3], [4, 5, 6]]
myList = [{'weights': new_weights}]

This returns: [{'weights': [[1, 2, 3], [4, 5, 6]]}]

How could one get the following?

[{'weights': [1, 2, 3]}, {'weights': [4, 5, 6]}]

Using a list comprehension as follows:

new_weights = [[1, 2, 3], [4, 5, 6]]
myList = [{'weights': new_weights}]

result = [
    {'weights': element}
    for element in new_weights
]
print(result)

Output:

[{'weights': [1, 2, 3]}, {'weights': [4, 5, 6]}]

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