开发者

Python: Build a dictionary from a file's contents

Say that I have a file of names and values with entries like this:

lasker:22,45,77,101
kramnik:45,22,15,105

What开发者_如何转开发's the most Pythonic way to get them into a dictionary with the name as the key and the values as a list like this:

{ 'lasker': (22,45,77,101), 'kramnik': (45,22,15,105) }

EDIT

And is there anyway to iterate through them in the order I read them from the file or would this require a different data structure?


I think it is pretty clear how this code works:

def get_entries( infile ):
    with open( infile, 'rt') as file:
        for line in file:
            name, nums = line.split(':', 1)
            yield name, tuple(int(x) for x in nums.split(','))

# dict takes a sequence of  `(key, value)` pairs and turns in into a dict
print dict(get_entries( infile ))

Writing a generator that yields pairs and passing it to dict is a extremely useful pattern.

If you just want to iterate over the pairs you can do this directly:

for name, nums in get_entries( infile ):
    print name, nums

but if you need dict access later but also ordering you can simply replace the dict with a OrderedDict:

from collections import OrderedDict
print OrderedDict(get_entries( infile ))


No need to care about lines with a regex:

import re

pat = re.compile('([a-z]+)\s*:\s*(\d+(?:\s*,\s*\d+)*)')

with open('rara.txt') as f:
    dic = dict((ma.group(1),map(int,ma.group(2).split(','))) for ma in pat.finditer(f.read()))

print dic

Tested with following text in 'rara.txt' file's text:

lasker :  22,45,  77,101 kramnik:888 ,22,15,105  kramniu :45,22,    3433,105 6765433 laskooo:22,45, 77 , 101  kooni:
45, 78 45kramndde:45,334 ,15,105 tasku: 22,45  ,7,101 krammma:  1105oberon glomo:22, 3478,77 ,101 draumnik:45,105 
toyku:22,45,7,101 solo
   ytrmmma:1105oberon radabidadada lftyker:22,3478,7,101

Result

{'laskooo': [22, 45, 77, 101], 'tasku': [22, 45, 7, 101], 'krammma': [1105], 'glomo': [22, 3478, 77, 101], 'kramniu': [45, 22, 3433, 105], 'kooni': [45, 78], 'lftyker': [22, 3478, 7, 101], 'toyku': [22, 45, 7, 101], 'kramnik': [888, 22, 15, 105], 'draumnik': [45, 105], 'ytrmmma': [1105], 'lasker': [22, 45, 77, 101], 'kramndde': [45, 334, 15, 105]}

EDIT: I modified the regex pattern (added \s* ) and the 'rara.txt' file's text

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜