python - 如何遍历嵌套的字典(计数器)并递归更新键
问题描述
我正在将文件中的数据读取到一系列列表中,如下所示:
sourceData = [[source, topic, score],[source, topic, score],[source, topic, score]...]
其中每个列表中的来源和主题可以相同或不同。
我想要实现的是一个字典,它将与每个来源相关的主题及其相关分数分组(然后将平均分数,但为了这个问题的目的,让我们将它们列为主题的值(键)) .
理想情况下,结果看起来像一个嵌套字典列表,如下所示:
[{SOURCE1:{TOPIC_A:SCORE1,SCORE2,SCORE3},
{TOPIC_B:SCORE1,SCORE2,SCORE3},
{TOPIC_C:SCORE1,SCORE2,SCORE3}},
{SOURCE2:{TOPIC_A:SCORE1,SCORE2,SCORE3},
{TOPIC_B:SCORE1,SCORE2,SCORE3},
{TOPIC_C:SCORE1,SCORE2,SCORE3}}...]
我认为最好的方法是创建一个来源的计数器,然后为每个来源的每个主题创建一个字典,并将每个字典保存为每个相应来源的值。但是,我无法正确迭代以获得所需的结果。
这是我到目前为止所拥有的:
sourceDict = {}
sourceDictList = []
for row in sourceData:
source = row[0]
score = row[1]
topic = row[2]
sourceDict = [source,{topic:score}]
sourceDictList.append(sourceDict)
sourceList.append(source)
其中sourceDictList
导致以下结果:([[source, {topic: score}]...],
基本上重新格式化来自原始列表列表的数据),并且sourceList
只是所有源的列表(一些重复)。
然后我初始化一个计数器并将计数器的源与源sourceDictList
匹配,如果它们匹配,则将topic:score
dict 保存为键:
sourceCounter = Counter(sourceList)
for key,val in sourceCounter.items():
for dictitem in sourceDictList:
if dictitem[0] == key:
sourceCounter[key] = dictitem[1]
但是输出只是将最后一个topic:score
字典保存到每个源。因此,而不是所需的:
[{SOURCE1:{TOPIC_A:SCORE1,SCORE2,SCORE3},
{TOPIC_B:SCORE1,SCORE2,SCORE3},
{TOPIC_C:SCORE1,SCORE2,SCORE3}},
{SOURCE2:{TOPIC_A:SCORE1,SCORE2,SCORE3},
{TOPIC_B:SCORE1,SCORE2,SCORE3},
{TOPIC_C:SCORE1,SCORE2,SCORE3}}...]
我只得到:
Counter({SOURCE1: {TOPIC_n: 'SCORE_n'}, SOURCE2: {TOPIC_n: 'SCORE_n'}, SOURCE3: {TOPIC_n: 'SCORE_n'}})
我的印象是,如果有一个唯一的密钥保存到一个字典中,它将附加该key:value
对而不覆盖以前的密钥。我错过了什么吗?
感谢您对此的任何帮助。
解决方案
简单地说,我们可以这样做:
sourceData = [
['source1', 'topic1', 'score1'],
['source1', 'topic2', 'score1'],
['source1', 'topic1', 'score2'],
['source2', 'topic1', 'score1'],
['source2', 'topic2', 'score2'],
['source2', 'topic1', 'score3'],
]
sourceDict = {}
for row in sourceData:
source = row[0]
topic = row[1]
score = row[2]
if source not in sourceDict:
# This will be executed when the source
# comes for the first time.
sourceDict[source] = {}
if topic not in sourceDict[source]:
# This will be executed when the topic
# inside that source comes for the first time.
sourceDict[source][topic] = []
sourceDict[source][topic].append(score)
print(sourceDict)
推荐阅读
- performance-testing - 为什么 web_reg_find 在 LoadRunner 中看不到某些静态文本?
- oracle - 如何为既是主键又是外键的同一列创建两个索引?
- reactjs - this.props 不会从 react/redux 加载数据
- bash - 从linux中文件的特定字符创建子文件夹
- r - Cox 比例风险模型-交互作用
- javascript - 如何修复节点 UnhandledPromiseRejectionWarning
- android - 图形在 libgdx 中占用 0.5 GB 内存
- javascript - 我们如何在 Angular 8 中添加链接?
- r - 使用具有多个条件的 gsub 替换 PDF 中的单词列表
- angular - Angular 组件和 ngOnInit 的自定义装饰器