我有这个字符串:
"{'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}
我如何获得此列表?
答案 0 :(得分: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})]
答案 1 :(得分:-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}}