首页 > 解决方案 > 从列表创建字典,覆盖重复键

问题描述

我在下面有我的代码。我正在尝试从从 txt 文件中提取的列表中创建字典,但循环会覆盖以前的信息:

f = open('data.txt','r')
lines = f.readlines()
lines = [line.rstrip('\n') for line in open('data.txt')]
columns=lines.pop(0)

for i in range(len(lines)):
    lines[i]=lines[i].split(',')

dictt={}
for line in lines:
    dictt[line[0]]=line[1:]

print('\n')
print(lines)
print('\n')
print(dictt)

我知道我必须玩:

for line in lines:
    dictt[line[0]] = line[1:]

部分,但我能做什么,我必须使用numpy吗?如果是这样,怎么做?

我的lines清单是:

[['USS-Enterprise', '6', '6', '6', '6', '6'],
['USS-Voyager', '2', '3', '0', '4', '1'],
['USS-Peres', '10', '4', '0', '0', '5'],
['USS-Pathfinder', '2', '0', '0', '1', '2'],
['USS-Enterprise', '2', '2', '2', '2', '2'],
['USS-Voyager', '2', '1', '0', '1', '1'],
['USS-Peres', '8', '5', '0', '0', '4'],
['USS-Pathfinder', '4', '0', '0', '2', '1']]

我的字典变成:

{'USS-Enterprise': ['2', '2', '2', '2', '2'],
'USS-Voyager': ['2', '1', '0', '1', '1'],
'USS-Peres': ['8', '5', '0', '0', '4'],
'USS-Pathfinder': ['4', '0', '0', '2', '1']}

只取最后一个,我想将这些值加在一起。我真的很困惑。

标签: python

解决方案


您正在尝试为同一个键附加多个值。您可以为此使用 defaultdict,或者修改您的代码并将该get方法用于字典。

for line in lines:
    dictt[line[0]] = dictt.get(line[0], []).extend(line[1:])

这将查找每个键,line[1:]如果键是唯一的,则分配,如果它是重复的,只需将这些值附加到以前的值上。


推荐阅读