Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

python - What is the most efficient way to match keys from a dictionary to data in text file

Say I have the following dictionary:

data=[a 1 : A, b 2 : B, c 3 : C, d 4 : D]

and a .txt file which reads:

Key      a 1  b 2  c 3  d 4
Word     as   box  cow  dig

(note values are seperated by TAB character)

How can I use the keys from the data dictionary to find the corresponding word from the .txt file? Ideally I would like to output a dictionary like:

data=[a 1 : as, b 2 : box, c 3 : cow, d 4 : dig]

Please ask for more info. if needed.

Thanks,

Alex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this:

with open('abc') as f:
    keys = map(str.strip, next(f).split('Key      ')[1].split('  '))
    vals = map(str.strip, next(f).split('Word     ')[1].split('	'))
    print dict(zip(keys,vals))
...     
{'d 4': 'dig', 'b 2': 'box', 'a 1': 'as', 'c 3': 'cow'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...