two Lists to Json Format in python

前端 未结 4 738
囚心锁ツ
囚心锁ツ 2020-12-09 19:56

I have two lists

a=[\"USA\",\"France\",\"Italy\"]
b=[\"10\",\"5\",\"6\"]

I want the end result to be in json like this.

[{\         


        
4条回答
  •  生来不讨喜
    2020-12-09 20:04

    Using list comprehension:

    >>> [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
    [{'country': 'USA', 'wins': '10'},
     {'country': 'France', 'wins': '5'},
     {'country': 'Italy', 'wins': '6'}]
    

    Use json.dumps to get JSON:

    >>> json.dumps(
    ...     [{'country': country, 'wins': wins} for country, wins in zip(a, b)]
    ... )
    '[{"country": "USA", "wins": "10"}, {"country": "France", "wins": "5"}, {"country": "Italy", "wins": "6"}]'
    

提交回复
热议问题