python - 在 python 中用子列表拆分字符串

标签 python string split

我有这个字符串:

"{'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}

我怎样才能得到这个列表?

最佳答案

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})]

关于python - 在 python 中用子列表拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15361073/

相关文章:

python - numpy nanmean 错误

Python 返回 map 对象

python - 如何用模式(正则表达式)替换部分字符串在数据框中抛出行

html - 如何在iOS中对html格式的字符串应用粗体?

python - 根据点拆分 Pandas 数据框中的一列

C++ 拆分字符串?

Python嵌套字典理解与if else

java - 减去两次后 TextView 上没有任何显示(hh :mm:ss)

c++ - string erase 使用向后迭代器追加元素

python - Pandas 数据框