Skip to content Skip to sidebar Skip to footer

Remove Quotes In Python Dictionary

I get a dictionary like following, {'members': '{'mgt.as.wso2.com': 4100,'as.wso2.com': 4300}', 'subdomain': 'mgt'} In the key members value is passed within two single quotes. Is

Solution 1:

Evaluate the string value with literal_eval, and then assign it back to the key:

>>> import ast
>>> d['members'] = ast.literal_eval(d['members'])
>>> d['members']['as.wso2.com']
4300

Solution 2:

import ast
d = {'clustering': 'true',
 'http_proxy_port': '80',
 'https_proxy_port': '443',
 'localmemberhost': '127.0.1.1',
 'localmemberport': '4100',
 'members': '{"mgt.as.wso2.com": 4100,"as.wso2.com": 4300}',
 'portoffset': '1',
 'stratos_instance_data_mgt_host_name': 'mgt.as.wso2.com',
 'stratos_instance_data_worker_host_name': 'as.wso2.com',
 'subdomain': 'mgt'}

print d
for k, v in d.items():
   if v[0] == '{' and v[-1] == '}':
      d[k] = ast.literal_eval(v)

print d

Post a Comment for "Remove Quotes In Python Dictionary"