Home > Software engineering >  How can I add list inside list in python json file?
How can I add list inside list in python json file?

Time:11-12

I pulled data from website with beautifulsoap in python. How can I add the letters in myList to the beginning of the data I pull? for example those starting with A like those starting with B ?

I tryed a few different things for this but I couldnt achieve.

the data seems like this.

[
    {
        "idiom": "above board",
        "meaning": "If something is above board, it's been done in a legal and honest way.",
        "examples": [
            "I'm sure the deal was completely above board as I know James well and he'd never do anything illegal or corrupt.",
            "The minister claimed all the appointments were above board and denied claims that some positions had been given to his friends."
        ]
    },

hear is my code :

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
import json

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
url = "https://www.englishclub.com/ref/Idioms/"


mylist = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W"
]

list = {}
data = []

for i in range(23):

    result = requests.get(url mylist[i] "/", headers = headers)
    doc = BeautifulSoup(result.text,"html.parser")

    for tag in doc.select('.linktitle a'):
        result = requests.get(tag['href'])
        doc = BeautifulSoup(result.text,"html.parser")
        data.append({
            'idiom': doc.h1.get_text(strip=True),
            'meaning': doc.select_one('h1 ~ h2   p').get_text(strip=True),
            'examples':[e.get_text(strip=True) for e in doc.select('main ul li')]
        })



with open('idioms.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

CodePudding user response:

Based on your comment, what you can do is create a temporary variable like tempdata inside your 1st for loop, something like,

for i in range(23):
    tempdata = []

Then you can instead of appending each idiom to data you would instead append to this temporary variable,

tempdata.append({...})

And finally add all the contents in the temporary variable into the data variable outside of the 2nd for loop,

data.append({mylist[i]: tempdata})
  • Related