我有一个以前输出到文本文件中的字典,即 [in]:
dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milka, whatever\tfood"""
最初,键是第 1 列,别名在第 2 列,第 3 列是值,我需要转换文本文件,使最后一列是键,第 1 列和第 2 列是值:
[出去]:
Foo bar language\tfoobar, foo, bar, foo foo
computing\tfoobar, foo, bar, foo foo, python, java, c, c++, prog
food\tcereal, milka, whatever\tedibles
这样做的目的是让给定输入foo foo
,按getkeybyvalue()
函数将返回['Foo bar language','computing']
。
我一直在东它如下:
from collections import defaultdict
outdict = defaultdict(list)
def getkeybyvalue(dictionary, value):
return [i for i,j in dictionary.items() if value in j]
dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milka, whatever\tfood"""
for line in dict_from_file.split('\n'):
column1, column2, column3 = line.strip().split('\t')
#print column1, column2, column3
for c3 in column3.split(','):
c3 = c3.strip(', ')
outdict[c3].append(column1)
for c2 in column2.split(','):
outdict[c3].append(c2.strip(' ,'))
for k in outdict:
print k, outdict[k]
print getkeybyvalue(outdict, 'foo foo')
- 有没有更简洁的方法来做到这一点?
- 我还应该如何阅读给定的文本文件
foo foo
,我的 python 字典返回['Foo bar language','computing']
?