Home > Mobile >  How to add to python dictionary without needing a key
How to add to python dictionary without needing a key

Time:03-16

I am scraping some information off the web and want to show write the information into a JSON file with this format:

[
    {
        "name" : "name1",
        "value" : 1
    },
    {
        "name" : "name2",
        "value" : 2
    },
    {
        "name" : "name3",
        "value" : 3
    },
    {
        "name" : "name4",
        "value" : 4
    },
    {
        "name" : "name5",
        "value" : 5
    }
]

I am looping through everything I am scraping but don't know how to convert that information to this format. I tried to create a dictionary and then add to it after every loop but it does not give me the output I want.

dictionary = None

name = None
value = None

for item in someList:
    name = item.name
    value = item.value

    dictionary[""] = {"name": name, "value": value}

with open("data.json", "w") as file:
    json.dump(dictionary, file, indent=4)

CodePudding user response:

Try this:

dictionary = [{"name": item.name, "value": item.value} for item in someList]

CodePudding user response:

The format you show is a list not a dictionary. So you can make a list and append to it the different dictionaries.

arr = []

for item in someList:
    dictionary.append({"name": item.name, "value": item.value})

with open("data.json", "w") as file:
    json.dump(array, file, indent=4)

CodePudding user response:

The answer was simpler than I thought. I just needed to make a list of dictionaries and use that list in the json.dumps() function. Like this:

myList = list()

name = None
value = None

for item in someList:
    name = item.name
    value = item.value

    myList.append({"name": name, "value": value})

with open("data.json", "w") as file:
    json.dump(myList, file, indent=4)
  • Related