Reputation:
I have one string having dictionary, I want to convert it into a list, but unable to remove single quote while doing the same.
Can someone help me in figuring out what is missing here?
>>> a = '{"src_ports": [7] , "dst_ports": [8]}'
What I want is following:
[{"src_ports": [7] , "dst_ports": [8]}]
But what I get is following:
>>> a = [a]
>>> a
['{"src_ports": [7] , "dst_ports": [8]}']
Edited: With ast, order of dictionary elements gets changed, I need to keep it intact.
>>> import ast
>>> b = [ast.literal_eval(a)]
>>> b
[{'dst_ports': [8], 'src_ports': [7]}]
Upvotes: 0
Views: 973
Reputation: 402413
ast.literal_eval
>>> import ast
>>> [ast.literal_eval(a)]
[{'src_ports': [7], 'dst_ports': [8]}]
json.loads
(Preserves order.)
>>> import collections
>>> import json
>>> [json.loads(a, object_pairs_hook=collections.OrderedDict)]
[OrderedDict([('src_ports', [7]), ('dst_ports', [8])])]
Note that an OrderedDict
is still a dictionary, so you can access its elements the same way you would a normal one.
Upvotes: 3
Reputation: 25789
You can use the ast.literal_eval()
function as a safer eval()
for that:
import ast
a = '{"src_ports": [7] , "dst_ports": [8]}'
b = [ast.literal_eval(a)]
# [{'dst_ports': [8], 'src_ports': [7]}]
UPDATE - Provided your structure remains the same, you can use the json
module in combination with collections.OrderedDict
if you want to preserve the order. Keep in mind that both Python dict
and JSON are, generally, unordered structures:
import json
import collections
a = '{"src_ports": [7] , "dst_ports": [8]}'
b = json.loads(a, object_pairs_hook=collections.OrderedDict)
But if you print it out it you'll get something like OrderedDict([(u'src_ports', [7]), (u'dst_ports', [8])])
however your order will be preserved, for example if you're serializing it later or loop through it.
Upvotes: 0