在python中将文本文件转换为字典

时间:2014-10-31 04:12:12

标签: python string dictionary text-files key-value

因此,我想将以下内容转换为第一列为键的字典,第二列为值。

http://pastebin.com/29bXkYhd

以下代码适用于此(假设romEdges.txt是文件的名称):

f = open('romEdges.txt')

dic = {}

for l in f:

    k, v = l.split()

    if k in dic:

        dic[k].extend(v)

    else:

        dic[k] = [v]

f.close()

但为什么代码不能用于此文件?

http://pastebin.com/Za0McsAM

如果有人能告诉我第二个文本文件的正确代码也能正常工作,我将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您应该使用append代替extend

from collections import defaultdict

d = defaultdict(list)

with open("romEdges.txt") as fin:
    for line in fin:
        k, v = line.strip().split()
        d[k].append(v)
print d

或使用集合来防止重复

d = defaultdict(set)

with open("romEdges.txt") as fin:
    for line in fin:
        k, v = line.strip().split()
        d[k].add(v)
print d

答案 1 :(得分:-1)

如果要将数据附加到字典,则可以在python中使用更新。请使用以下代码:

  f = open('your file name')

 dic = {}

 for l in f:

    k,v = l.split()

    if k in dic:

       dict.update({k:v })

    else:

       dic[k] = [v]

打印dic f.close()

输出:

 {'0100464': ['0100360'], '0100317': ['0100039'], '0100405': ['0100181'], '0100545': ['0100212'], '0100008': ['0000459'], '0100073': ['0100072'], '0100044': ['0100426'], '0100062': ['0100033'], '0100061': ['0000461'], '0100066': ['0100067'], '0100067': ['0100164'], '0100064': ['0100353'], '0100080': ['0100468'], '0100566': ['0100356'], '0100048': ['0100066'], '0100005': ['0100448'], '0100007': ['0100008'], '0100318': ['0100319'], '0100045': ['0100046'], '0100238': ['0100150'], '0100040': ['0100244'], '0100024': ['0100394'], '0100025': ['0100026'], '0100022': ['0100419'], '0100009': ['0100010'], '0100020': ['0100021'], '0100313': ['0100350'], '0100297': ['0100381'], '0100490': ['0100484'], '0100049': ['0100336'], '0100075': ['0100076'], '0100074': ['0100075'], '0100077': ['0000195'], '0100071': ['0100072'], '0100265': ['0000202'], '0100266': ['0000201'], '0100035': ['0100226'], '0100079': ['0100348'], '0100050': ['0100058'], '0100017': ['0100369'], '0100030': ['0100465'], '0100033': ['0100322'], '0100058': ['0100056'], '0100013': ['0100326'], '0100036': ['0100463'], '0100321': ['0100320'], '0100323': ['0100503'], '0100003': ['0100004'], '0100056': ['0100489'], '0100055': ['0100033'], '0100053': ['0100495'], '0100286': ['0100461'], '0100285': ['0100196'], '0100482': ['0100483']}