如何读取共享同一个密钥的文本文件和组值

问题描述 投票:0回答:2

我需要阅读该文件num.txt文件,并将它们组合在一起无论他们使用像d {},不使用defaultdict词典共享同一个密钥

我需要输出一个:{ '0':{ '5', '1', '6', '2'}, '4':{ '3'}, '9':{ '12','11 ”,'10 '}, '6':{' 4 '}, '5':{' 4' , '3'}, '11':{ '12'}, '7':{ '8'} }

0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
python python-3.x dictionary
2个回答
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']})

0
投票

您可以使用csvdefaultdict模块为好。

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'}}
© www.soinside.com 2019 - 2024. All rights reserved.