我需要读取此文件num.txt文件,并使用d {}这样的字典(而不是使用defaultdict)将它们组合在一起,以了解它们是否共享相同的密钥
我需要输出: {'0':{'5','1','6','2'},'4':{'3'},'9':{'12','11','10'} ,'6':{'4'},'5':{'4','3'},'11':{'12'},'7':{'8'}}
OPTIONS
答案 0 :(得分:1)
使用collections.defaultdict
:
from collections import defaultdict
d = defaultdict(list)
with open('num.txt') as f:
for line in f:
key, value = line.strip().split()
if key in d:
d[key].append(value)
else:
d[key] = [value]
print(d)
# defaultdict(<class 'list'>, {'0': ['5', '1', '2', '6'],
# '4': ['3'],
# '9': ['12', '10', '11'],
# '6': ['4'],
# '5': ['4', '3'],
#. '11': ['12'],
# '7': ['8']})
答案 1 :(得分:0)
您也可以使用csv
和defaultdict
模块。
from collections import defaultdict
import csv
d = defaultdict(set)
with open('filename.txt', 'r') as f:
r = csv.reader(f, delimiter=' ')
for k, v in r: d[k].add(v)
d = dict(d)
#{'0': {'5','1','6','2'}, '4': {'3'}, '9': {'12','11','10'}, '6': {'4'}, '5': {'4','3'}, '11': {'12'}, '7':{'8'}}