'How to stop the data in my variables moving to a new line with JSON in python

I am trying to keep my data from variable on the same line when its output in JSON, here is my code -

import json
numbers = [2,'g',5,2,'k',1,'a',5,7,'o',9,8,'h',3,4,'e',4,10,'y']

def remove_duplicates(duplist):
    noduplist = []
    for element in duplist:
        if element not in noduplist:
            noduplist.append(element)
        
    return noduplist

from collections import defaultdict
d = defaultdict(list)
for x in remove_duplicates(numbers):
    d[type(x)].append(x)

number = (d[int])
letters = (d[str])

number.sort()
letters.sort()
list = (number + letters)
total = sum(number)
string_count = len(letters)


output = {"List": list, "total": total, "string_count": string_count, "integers": number, "strings": letters}

print(json.dumps(output, indent=2))

Its out put is -

{
  "List": [
    1,
    2,
    3,
    4,
    5,
    7,
    8,
    9,
    10,
    "a",
    "e",
    "g",
    "h",
    "k",
    "o",
    "y"
  ],
  "total": 49,
  "string_count": 7,
  "integers": [
    1,
    2,
    3,
    4,
    5,
    7,
    8,
    9,
    10
  ],
  "strings": [
    "a",
    "e",
    "g",
    "h",
    "k",
    "o",
    "y"
  ]
}

But i need it to look like this -

"list": [1,2,3,4,5,7,8,9,10,'a','e','g','h','k','o','y']

Where am i going wrong? I have searched forums and documentation but cant see how to stop it



Solution 1:[1]

Two things:

First, you are printing an object that have multiple keys (List, total, string_count etc). Printing that object will always display all the keys and values you put into that object.

If you only want the List part of that object, you should print that specific key, like so:

print(json.dumps(output["List"]))

Output: [1, 2, 3, 4, 5, 7, 8, 9, 10, "a", "e", "g", "h", "k", "o", "y"]

You don't have to use json.dumps, you can just print(output["List"] with the following result: [1, 2, 3, 4, 5, 7, 8, 9, 10, 'a', 'e', 'g', 'h', 'k', 'o', 'y']

Note the difference: the former is valid json (using double quotes on strings) and the second is just a python list (using single quotes on strings).

Lastly, printing with an indent=2 will result in a more readable form of your object (or in your case, an undesirable format).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JarroVGIT