如何在python 3中将字典对象转换为字符串

时间:2018-03-22 12:12:55

标签: string python-3.x dictionary converter

我有嵌套字典,我需要将此字典串起来

字典示例

data = {
  'filter': {
      'operator': "and",
      'filters': [{
          'operator': "or",
          'filters': [{
              'operator': "and",
              'filters': [{
                  'value': "blue"
              }, {
                  'value': "green"
              }]
          }, {
              'operator': "and",
              'filters': [{
                  'value': "brown"
              }, {
                  'value': "green"
              }]
          }, {
              'value': "green"
          }]
      }, {
          'value': "red"
      }]
    }
}

我使用递归函数获取'过滤器'键,但我需要检测括号级别

def recursively(dct, field):

    if field in dct:
        yield dct[field]
    for k in dct:
        if isinstance(dct[k], list):
            for i in dct[k]:
                for j in recursively(i, field):
                    yield j

最后我需要字符串输出

>>> recursivaly(data['filter'], 'filters')
# result
((blue AND green) OR (brown AND green) OR green) AND NOT red
你可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

你可以做这样的事情

def dict2str(d):
    if 'value' in d:
        return d['value']
    elif 'operator' in d and 'filters' in d:
        return '(' + (" " + d['operator'].upper() + " ").join(map(dict2str, d['filters'])) + ')'
    else:
        raise Exception('invalid dictionary')

基本上递归地沿着字典向下并返回每个节点的字符串表示。简化第二个if这里是一个更明确的等效代码:

def dict2str(d):
    if 'value' in d:
        return d['value']
    elif 'operator' in d and 'filters' in d:

        operator = " " + d['operator'].upper() + " "

        filters = []
        for filt in d['filters']:
            filters.append(dict2str(filters))

        ret = ""
        ret += "("
        ret += operator.join(filters)
        ret += ")"

        return ret
    else:
        raise Exception('invalid dictionary')

"AND NOT red"部分让我感到困惑,但我希望这会有所帮助