search

Home  >  Q&A  >  body text

python列表转json格式

例:list=['a','b'],['c','d'],...
例输出:{{'aa':'a','bb':'b'},{'cc':'c','dd':'d'},...}
需要输出为json格式,以及给value一个key。
怎么写好,谢谢了。

我猜测的提问
例如:

l = ['a', 'b'], ['c', 'd']

输出:

{
    "k1": [
        {"a": "a"},
        {"b": "b"}
    ],
    "k2": [
        {"c": "c"},
        {"d": "d"}
    ]
}
天蓬老师天蓬老师2802 days ago1368

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-18 09:24:45

    Is this the effect you want?

    l=[['a','b'],['c','d']]
    ret = []
    for i in l:
        item = {}
        for j in i:
            item[j*2] = j
        ret.append(item)
            
    print ret
    import json
    print json.dumps(ret)
    
    

    [{'aa': 'a', 'bb': 'b'}, {'cc': 'c', 'dd': 'd'}]
    [{"aa": "a", " bb": "b"}, {"cc": "c", "dd": "d"}]

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:24:45

    import json
    list=['a','b'],['c','d']
    result = [{value*2:value for value in i} for i in list]
    print(json.dumps(result))  # '[{"aa": "a", "bb": "b"}, {"cc": "c", "dd": "d"}]'

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:24:45

    import json
    
    def main(list_):
        return json.dumps([{'{key}{key}'.format(key=k): k for k in lst} for lst in (i for i in list_)])
    
    
    if __name__ == '__main__':
        list_=['a','b'],['c','d']
        print main(list_)     # '[{"aa": "a", "bb": "b"}, {"cc": "c", "dd": "d"}]'

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:24:45

    I don’t understand your intention, please describe the problem clearly

    reply
    0
  • Cancelreply