【问题标题】:Remove quotes in python dictionary删除python字典中的引号
【发布时间】:2015-05-06 04:30:35
【问题描述】:

我得到一个像下面这样的字典,

{'members': '{"mgt.as.wso2.com": 4100,"as.wso2.com": 4300}', 'subdomain': 'mgt'}

在键成员中,值在两个单引号内传递。有没有办法删除那些单引号。我想要像下面这样的字典,

{'members': {"mgt.as.wso2.com": 4100,"as.wso2.com": 4300}, 'subdomain': 'mgt'}

【问题讨论】:

  • 那些字典是一样的,不是吗?
  • 你想打印第二个例子格式的字典吗?因为字典本身是一样的。还是您希望能够解析任一字典?
  • 没有。第一个包含 'members': '{"mgt.as.wso2.com": 4100,"as.wso2.com": 4300}' 我需要如下没有单引号成员:{"mgt.as.wso2 .com": 4100,"as.wso2.com": 4300}
  • 您希望该值本身成为字典吗?
  • @AnubianNoob 我想解析字典。为了做到这一点,我需要第二种格式的字典。

标签: python python-2.7 dictionary


【解决方案1】:
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

【讨论】:

  • 我会选择ast.literal_eval() 而不是eval()
  • @TigerhawkT3 是的,你说得对,我不知道(已修复)
【解决方案2】:

literal_eval评估字符串值,然后将其分配回键:

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

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多