使用 zip 将列表转换为字典

Convert list using zip to dictionary

当我将列表转换为字典时,字典中只存储了一个元素,我不知道为什么。这是我的代码。我在网络抓取中使用 BeautifulSoup 并存储在列表中。最后,我想清理它们并将它们存储在 JSON 文件

data = []

qa_dict={}

q_text=[]

q_username=[]
q_time=[]
r_text=[]

for i in range(1,2):
    print(i)

    url='https://drakhosravi.com/faq/?cat=all&hpage='+str(i)
    response1 = requests.get(url).content.decode()

    soup = BeautifulSoup(response1,'html.parser')

    for s in soup.select('span.hamyar-comment-person-name') :
        if(s.text!='دکتر آرزو خسروی'):
          q_username.append(s.text.strip())

    for times in soup.select('div.comment-header'):
            for s in times.select('span.hamyar-comment-date') :
                q_time.append(s.text.strip())

    question=[]
    for comment in soup.select('div.comment-body'):
        question.append(comment.text.strip())

    q_text=question[0::2]

    for r in soup.select('ol.faq-comment_replies'):
        for head in r.select('li'):
          for t in head.select('div.comment-body'):
            r_text.append(t.text.strip())

    for username,qtime,qtxt,rtxt in zip(q_username,q_time,q_text,r_text):

        qa_dict= {'username':username,'question_time':qtime,'question_text':qtxt,'url':url,'respond_text':rtxt,'responder_profile_url':'https://drakhosravi.com/about-us'}

    data.append(qa_dict)

with open('drakhosravi2.json', 'w+', encoding="utf-8") as handle:
    json.dump(qa_dict, handle, indent=4, ensure_ascii=False)

你的代码很难理解,但你的问题似乎很明确,所以这里有一个更通用的答案: 当您需要从列表创建字典时,我假设您在列表中有键列表,在另一个列表中有匹配值列表:

keys_sample = ["left", "right", "up", "down"]
values_sample = ["one", "two", 0, None]

# dictionary constructor takes pairs, which are the output of zip:
together = dict(zip(keys_sample, values_sample))

结果应该是这样的:

together = {'left': 'one', 'right': 'two', 'up': 0, 'down': None}

这里要记住的最重要的事情是两个列表必须具有相同的长度,并且按自然顺序迭代将匹配键值对。

我不完全理解您的问题,但您似乎希望 qa_dict 将列表作为值。但那是因为 qa_dict 在每次迭代中都会更新,而不会保存下一个值。改变这个

for username,qtime,qtxt,rtxt in zip(q_username,q_time,q_text,r_text):
  qa_dict={'username':username,'question_time':qtime,'question_text':qtxt,'url':url,'respond_text':rtxt,'responder_profile_url':'https://drakhosravi.com/about-us'}

qa_dict={'username':q_username,'question_time':q_time,'question_text':q_txt,'url':url,'respond_text':r_txt,'responder_profile_url':'https://drakhosravi.com/about-us'}

换句话说,不需要循环。由于其中每一个都是一个列表,您现在将在字典 qa_dict 中拥有列表作为值。

或者,如果您想创建字典列表,请将 data.append(qa_dict) 放入 for 循环中。