i would like to make list like below
data2 = ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']
from this list
data = [
{29: 'Run'},
{29: 'Read'},
{30: 'Sing'},
{30: 'Read'},
{31: 'Run'},
{31: 'Sing'},
{31: 'Read'},
{32: 'Read'}]
can anyone help me
People, please read the question correctly. The OP is asking how to collect the strings of different dicts with the same key into a single string.
I am a bit wondering how you would end up with a list of dicts like that, and not something like
data = [
{29: 'Run', 30: 'Sing', 31: 'Read', 32: 'Read'},
{29: 'Read', 30: 'Read', 31: 'Run'},
{31: 'Sing')]
which is basically the same, but that is besides the point.
You can easily do what you want with the following:
data = [
{29: 'Run'},
{29: 'Read'},
{30: 'Sing'},
{30: 'Read'},
{31: 'Run'},
{31: 'Sing'},
{31: 'Read'},
{32: 'Read'}]
# Create empty dict for all keys
key_dct = {}
# Loop over all dicts in the list
for dct in data:
# Loop over every item in this dict
for key, value in dct.items():
# Add value to the dict with this key
key_dct.setdefault(key, []).append(value)
# Combine all items in key_dct into strings
data2 = [', '.join(value) for value in key_dct.values()]
# Print data2
print(data2)
Output: ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']
Note that my solution works even if some of the dicts contain more than a single item.
EDIT: If you want to be certain that the order of the strings are also in the numerical order of the keys, then replace the creation of data2
in the snippet above with
# Sort items on their key values
items = list(key_dct.items())
items.sort(key=lambda x: x[0])
# Combine all items into strings
data2 = [', '.join(value) for _, value in items]
You can use collections.defaultdict
to put the same key value inside a list and then concatenate those value.
from collections import defaultdict
result = defaultdict(list)
for d in data:
for k, v in d.items():
result[k].append(v)
result = [", ".join(value) for _, value in result.items()]
print(result)
Output:
['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']
Do you mean like:
data2 = [list(d.values())[0] for d in data]
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.