Python字典在for循环中

huangapple go评论142阅读模式
英文:

Python Disctionary In For Loop

问题

我正在尝试制作一个小项目来提高自己。在编写代码时,我不明白其中的一个部分。

我正在从一个网站上爬取数据,并使用for循环打印数据。我获取每位运动员的UFC链接。系统运行得非常好,没有问题。我通过他们的姓名为每位运动员添加了一个ID。我使用一个字典来存储他们的ID号码

问题是,当我将字典用作 id[x] = href['href'] 时,代码运行得非常好

> 它会打印出我在输入框中键入的任何内容(选择)

然而,当我尝试将其用作 id = {x : href['href'] 时,代码无法正常工作

> 它只打印最后一个键的最后一个值。

所以我的问题是,为什么我无法使用 id = {x : href['href'] 方法获取特定的 href

这是可以尝试的工作代码

import requests
from bs4 import BeautifulSoup

input2 = str(input('输入运动员的姓名: '))

payload = {'gender':'All', 'search':input2}
session = requests.Session()
p = session.get('https://www.ufc.com/athletes/all?', params=payload)

soup2 = BeautifulSoup(p.text, 'html.parser')

specific_athlete = soup2.find_all('div','c-listing-athlete-flipcard__inner')
id = {}
for x, a in enumerate(specific_athlete, 1):
    specific_athlete = a.find('span','c-listing-athlete__name')

    href = a.find('a', 'e-button--black')

    #{key : value}
    id[x] = href['href']

    print(specific_athlete.text, ': ', href['href'], '\n', x) 

choose = int(input('选择哪位运动员(输入编号): '))
print(id[choose])

希望这能帮助解决你的问题。

英文:

I am trying to make small project to improve myself. I couldnt understand one part while I was coding.

I am scraping the data from a website and I print data with a for loop. I get the UFC links for every athlete. System works very nice and there is no problem. I put id for every athlete when I print them by their name. I use a dictionary for their id number.

The problem is when I use dictionary as; id[x] = href['href'] the code works excellent

> it prints whatever I type in input(choose)

However when I try to use it as; id = {x : href['href'] the code doesnt work properly

> just prints last value of the last key.

So my question is, why I cant get the specific href with the method of id = {x : href['href']

this is the working code you can try it

import requests
from bs4 import BeautifulSoup

input2 = str(input('type the name of the athlete: '))

payload = {'gender':'All', 'search':input2}
session = requests.Session()
p = session.get('https://www.ufc.com/athletes/all?', params=payload)

soup2 = BeautifulSoup(p.text, 'html.parser')

spesific_athlete = soup2.find_all('div','c-listing-athlete-flipcard__inner')
id = {}
for x, a in enumerate(spesific_athlete, 1):
    spesific_athlet = a.find('span','c-listing-athlete__name')
    
    href = a.find('a', 'e-button--black')

    #{key : value}
    id[x] = href['href']

    print(spesific_athlet.text, ': ', href['href'], '\n', x) 

choose = int(input('Which athlete do you choose(type a number): '))
print(id[choose])

答案1

得分: 1

当你使用 id[x] = href['href'] 时,你为每个运动员在 id 字典中添加一个新的键值对。所以,在循环结束时,你会得到一个包含所有运动员 href 值的字典。

然而,当你使用 id = {x: href['href']} 时,你在每次循环迭代中重新定义整个 id 字典。因此,在循环结束时,字典中只包含最后一个运动员的 href 值。

要修复这个问题,你可以继续使用 id[x] = href['href'] 来向字典添加新的键值对,就像之前那样。以下是已编辑的代码:

import requests
from bs4 import BeautifulSoup

input2 = str(input('输入运动员的姓名:'))

payload = {'gender':'All', 'search':input2}
session = requests.Session()
p = session.get('https://www.ufc.com/athletes/all?', params=payload)

soup2 = BeautifulSoup(p.text, 'html.parser')

specific_athlete = soup2.find_all('div','c-listing-athlete-flipcard__inner')
id = {}
for x, a in enumerate(specific_athlete, 1):
    specific_athlete = a.find('span','c-listing-athlete__name')
        
    href = a.find('a', 'e-button--black')

    #{key : value}
    id[x] = href['href']

    print(specific_athlete.text, ': ', href['href'], '\n', x) 

choose = int(input('选择哪位运动员(输入编号):'))
print(id[choose])
英文:

When you use id[x] = href['href'], you're adding a new key-value pair to the id dictionary for each athlete. So, by the end of the loop, you have a dictionary with all the athletes' href values stored.

However, when you use id = {x: href['href']}, you're redefining the entire id dictionary in every iteration of the loop. So, by the end of the loop, you only have the last athlete's href value stored in the dictionary.

To fix this, you can use id[x] = href['href'] to add a new key-value pair to the dictionary, just like you did before. Here's the edited code:

import requests
from bs4 import BeautifulSoup

input2 = str(input('type the name of the athlete: '))

payload = {'gender':'All', 'search':input2}
session = requests.Session()
p = session.get('https://www.ufc.com/athletes/all?', params=payload)

soup2 = BeautifulSoup(p.text, 'html.parser')

spesific_athlete = soup2.find_all('div','c-listing-athlete-flipcard__inner')
id = {}
for x, a in enumerate(spesific_athlete, 1):
    spesific_athlet = a.find('span','c-listing-athlete__name')
    
    href = a.find('a', 'e-button--black')

    #{key : value}
    id[x] = href['href']

    print(spesific_athlet.text, ': ', href['href'], '\n', x) 

choose = int(input('Which athlete do you choose(type a number): '))
print(id[choose])

huangapple
  • 本文由 发表于 2023年4月7日 00:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定