【问题标题】:Convert list using zip to dictionary使用 zip 将列表转换为字典
【发布时间】:2022-01-16 05:29:39
【问题描述】:

当我将列表转换为字典时,字典中只存储了一个元素,我不知道为什么。这是我的代码。我在网页抓取中使用 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)

【问题讨论】:

  • 您在每次 for 迭代中重写 qa_dict。创建一个字典列表并附加你的新字典

标签: python json beautifulsoup zip


【解决方案1】:

我不完全理解您的问题,但您似乎希望 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 循环。

【讨论】:

    【解决方案2】:

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

    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}
    

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

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2017-04-23
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 2015-07-23
      相关资源
      最近更新 更多