python - 从列表创建字典,覆盖重复键
问题描述
我在下面有我的代码。我正在尝试从从 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']}
只取最后一个,我想将这些值加在一起。我真的很困惑。
解决方案
您正在尝试为同一个键附加多个值。您可以为此使用 defaultdict,或者修改您的代码并将该get
方法用于字典。
for line in lines:
dictt[line[0]] = dictt.get(line[0], []).extend(line[1:])
这将查找每个键,line[1:]
如果键是唯一的,则分配,如果它是重复的,只需将这些值附加到以前的值上。
推荐阅读
- linux - 循环遍历子目录并为每个子目录创建 jpg 的 PDF
- javascript - 从数组中填写表格
- reactjs - 如果用户已经登录,当用户刷新页面时重定向到 React js 中的仪表板页面
- mysql - 使用 JOIN 创建视图,由于其他表只有几个匹配项,因此无法正常工作
- javascript - HTML/Javascript Openweather 应用程序信息未显示
- java - 过滤后的流永远不会返回
- c# - 实体框架强制 id[key] 插入
- sockets - 关于 SSL_connect 和 HTTPS 的查询
- r - 创建一个新列以识别两列是否相同但在第三列中具有不同的值
- reactjs - .htaccess 如何使用参数重定向到 index.html 但参数值与文件夹名称相同