convert list conatining strings to dictionary in python

Viewed 47

I have a list that has strings in it, in the form of key:value pairs, something like this

d = ['"id.resp_h": [loopback, unicast, multicast, interface_local_multicast, link_local_unicast, link_local_multicast, unspecified]',
 '"id.orig_h": {{ sensor_subnets }}']

and I need to convert it into a dictionary. I've tried many solutions like using json.loads() or ast.literal_eval() but none work.

Any suggestions??

Thanks:)

1 Answers

As far as I know, {{sensor_subnets}} is not a valid syntax, and it'll throw the exception TypeError: unhashable type: 'set'. Another problem is that the values in the list are not string, and they're interpreted as variables.

if you convert the values in the list to strings, and also change {{sensor_subnets}} to {"sensor_subnets"}, you can use the ast.literal_eval.

appropriate d should be like this:

d = ['"id.resp_h": ["loopback", "unicast", "multicast", "interface_local_multicast", "link_local_unicast", "link_local_multicast", "unspecified"]', '"id.orig_h": {"sensor_subnets"}']
import ast
out_dict = {}
for key_val in d:
   new_dict = ast.literal_eval("{"+key_val+"}")
   out_dict.update(new_dict)
print(out_dict)

output:

{'id.resp_h': ['loopback', 'unicast', 'multicast', 'interface_local_multicast', 'link_local_unicast', 'link_local_multicast', 'unspecified'], 'id.orig_h': {'sensor_subnets'}}
Related