我被严重卡住,希望能得到指向正确方向的手电筒。我有一个要导入为文本文件的列表。它有名称,每一行都有编号。名称重复1、2或3次。 目标是使输出为{Key:[,,] ...}。我只设法显示了其中一个值。
dictionary = {}
with open('%Filename%') as f:
for line in f:
num, key = line.strip().split()
dictionary[key] = [num]
print(dictionary)
我希望输出为{'USA': ['15','91','99']...}
相反,我只得到{'USA': ['99]...}
答案 0 :(得分:1)
使用collection.defaultdict
例如:
from collections import defaultdict
dictionary = defaultdict(list)
with open('%Filename%') as f:
for line in f:
num, key = line.strip().split()
dictionary[key].append(num)
print(dictionary)
或dict.setdefault
例如:
dictionary = {}
with open('%Filename%') as f:
for line in f:
num, key = line.strip().split()
dictionary.setdefault(key, []).append(num)
print(dictionary)
list.append
将元素添加到列表中。 答案 1 :(得分:1)
dictionary = {}
with open('%Filename%') as f:
for line in f:
num, key = line.strip().split()
if not key in dictionary:
dictionary[key] = []
dictionary[key].append(num)
print(dictionary)
答案 2 :(得分:0)
使用dict.get可以轻松解决此问题:
dictionary = {}
with open('%Filename%') as f:
for line in f:
num, key = line.strip().split()
dictionary[key] = dictionary.get(key, []) + [num]
print(dictionary)