1

我有这个字符串:

"{'osFreeMem': 286494720, 'osUpTime': 19230718, 'sysload': [0.24609375, 0.62109375, 0.734375], 'nodeUpTime': 1831, 'osTotMem': 536870912, 'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760}}"

我想要一本包含这些值的字典:

'osFreeMem': 286494720
'osUpTime': 19230718
'sysload': [0.24609375, 0.62109375, 0.734375]    
'nodeUpTime': 1831
'osTotMem': 536870912    
'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760}

我怎样才能得到这个清单?

4

2 回答 2

5
In [37]: s = "{'osFreeMem': 286494720, 'osUpTime': 19230718, 'sysload': [0.24609375, 0.62109375, 0.734375], 'nodeUpTime': 1831, 'osTotMem': 536870912, 'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760}}"

In [38]: import ast

In [39]: d = ast.literal_eval(s)

In [40]: d
Out[40]: 
{'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760},
 'nodeUpTime': 1831,
 'osFreeMem': 286494720,
 'osTotMem': 536870912,
 'osUpTime': 19230718,
 'sysload': [0.24609375, 0.62109375, 0.734375]}

In [41]: d.items()
Out[41]: 
[('osFreeMem', 286494720),
 ('osUpTime', 19230718),
 ('sysload', [0.24609375, 0.62109375, 0.734375]),
 ('nodeUpTime', 1831),
 ('osTotMem', 536870912),
 ('nodeMemory', {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760})]

或者

In [44]: import json

In [45]: json.loads(s.replace("'",'"')).items()
Out[45]: 
[(u'osFreeMem', 286494720),
 (u'osUpTime', 19230718),
 (u'sysload', [0.24609375, 0.62109375, 0.734375]),
 (u'nodeUpTime', 1831),
 (u'osTotMem', 536870912),
 (u'nodeMemory', {u'heapTotal': 8766304, u'heapUsed': 7789588, u'rss': 22773760})]
于 2013-03-12T12:25:10.753 回答
-1

您还可以使用内置函数eval

>>>d = eval("{'osFreeMem': 286494720, 'osUpTime': 19230718, 'sysload': [0.24609375, 0.62109375, 0.734375], 'nodeUpTime': 1831, 'osTotMem': 536870912, 'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760}}")
>>>d
{'osFreeMem': 286494720, 'osUpTime': 19230718, 'sysload': [0.24609375, 0.62109375, 0.734375], nodeUpTime': 1831, 'osTotMem': 536870912, 'nodeMemory': {'heapTotal': 8766304, 'heapUsed': 7789588, 'rss': 22773760}}
于 2013-03-12T12:51:40.707 回答