将具有多个值的perl哈希转换为python dict

时间:2017-04-19 12:45:03

标签: python perl dictionary data-structures hash

我在C:\Perl\test\ips.pl有一个名为ips.pl的perl文件,其中包含6个perl哈希值。每个哈希包含1个键和2个值。 该文件包含以下数据。

{
 '192.168.111.1' => [
            '192.168.111.2',
            '192.168.111.3',
 ],

 '192.168.111.4'  =>  [
                    '192.168.111.5',
                    '192.168.111.6',
 ],

 '192.168.111.7' => [
                     '192.168.111.8',
                     '192.168.111.9',
 ],
}

如何将此perl文件转换为python可读?我需要3个单独的Python Dict的结果。所需的结果应该是

dict1 = {'192.168.111.1': '192.168.111.2'}
dict2 = {'192.168.111.1': '192.168.111.3'}
dict3 = {'192.168.111.4': '192.168.111.5'}
dict4 = {'192.168.111.4': '192.168.111.6'}
dict5 = {'192.168.111.7': '192.168.111.8'}
dict6 = {'192.168.111.7': '192.168.111.9'}

作为perl和python的新手,请向我推荐任何模块,这对我来说都是一个简单的解决方案。如果我们没有这样的模块,那么请建议我的步骤。提前致谢

我尝试使用以下代码,

import re
class PerlLikeDict( dict ):
pattern_type= type(re.compile(""))
def getitem(self, key):
    F = open("resources.pl", "r+")
    print "value of F object is", F
    print "type of object is ", type(F)
    rd=str(F.read())
    print "value of string variable rd is", rd
    #print "value of 1st is", rd[1]
    #print dict_rd == dict(rd)
    if key in self:
        return super( PerlLikeDict, self ).__getitem__( key )
    for k in self:
        if type(k) == self.pattern_type:
            if k.match(key):
                return self[k]
    raise KeyError( "key %r not found" % ( key, ) )

F = open("resources.pl", "r+")
rd=str(F.read())
print "able to read the file", rd
x=PerlLikeDict(rd)
print x

这是错误

Traceback (most recent call last):
File "C:\Users\sanjaya.sahoo\workspace\my python 
learning\src\workon_local_perlfile.py", line 23, in <module>
x=PerlLikeDict(rd)
ValueError: dictionary update sequence element #0 has length 1; 2 is required

0 个答案:

没有答案