如何在python中向dic内的列表添加值

2024-10-04 11:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将字符串附加到字典中的列表中,以便每个参与者都有一个单词列表。这是我的密码:

words = [
    {'word': 'we', 'start_time': 90, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': "haven't", 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'even', 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'spoken', 'start_time': 91, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'about', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'your', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'newest', 'start_time': 92, 'participant': 'str_MIC_Y6E6_con_VnGhveZbaS'},
    {'word': 'some word here', 'start_time': 45, 'participant': 'other user'}
]

words.sort(key=lambda x: x['start_time'])

clean_transcript = []
wordChunk = {'participant': '', 'words': []}
for w in words:
    if wordChunk['participant'] == w['participant']:
        wordChunk['words'].append(w['word'])

    else:
        wordChunk['participant'] = w['participant']
        print(wordChunk['participant'])
        wordChunk['words'].append(w['word'])

clean_transcript.append(wordChunk)

这给了我一个结果:

[{'participant': 'str_MIC_Y6E6_con_VnGhveZbaS', 'words': ['some word here', 'we', "haven't", 'even', 'spoken', 'about', 'your', 'newest']}]

所以some word here在一个错误的列表中。我需要如何修改它来为other user创建自己的单词列表


Tags: 列表heretimesomeconstartwordwords
2条回答

您可以使用itertools.groupby

from itertools import groupby

res = []
words = sorted(words, key = lambda x: x['start_time'])
for k, g in groupby(words, key = lambda x: x['participant']):
    d = {'participant': k, 'words': [x['word'] for x in g]} 
    res.append(d)
print(res)

输出:

[{'participant': 'other user', 'words': ['some word here']}, {'participant': 'str_MIC_Y6E6_con_VnGhveZbaS', 'words': ['we', "haven't", 'even', 'spoken', 'about', 'your', 'newest']}]

使用列表理解

res = [{'participant': k, 'words': [x['word'] for x in g]} for k, g in
       groupby(sorted(words, key=lambda x: x['start_time']), key=lambda x: x['participant'])]

您可以重新构建数据结构,只需将其存储在参与者作为密钥的dict中:

wordChunk = {}
for w in words:
    wordChunk.setdefault(w["participant"],[]).append(w["word"])

wordChunk现在是一个dict,参与者作为键:

>>> wordChunk
{'str_MIC_Y6E6_con_VnGhveZbaS': ['we', "haven't", 'even', 'spoken', 'about', 'your', 'newest'], 'other user': ['some word here']}

相关问题 更多 >