当键值相同时,如何将数据追加到python dict中?

2024-04-26 03:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一些数据存储到dict中,但是所有值的键都是相同的,我尝试了update(),但是如果dict中已经存在了键,则更新忽略。如果有人解释如何附加具有相同键值的数据,那就太好了!你知道吗

这是我正在尝试的代码

from bs4 import BeautifulSoup
import requests

data = {}
proxy_url = 'https://free-proxy-list.net/'
req = requests.get(proxy_url)
soup = BeautifulSoup(req.content,'lxml')
table = soup.findAll('table')[0].findAll('tr')
for i in table:
    ip = i.select('td:nth-of-type(1)')
    port = i.select('td:nth-of-type(2)')

    if ip:
        ipx = ip[0].text

    if port:
        portx = port[0].text
        proxy = ('http//'+ipx+':'+portx).encode('utf-8')
        data.update({'http':proxy})

print(data)

我想要的输出命令:

data = {
  'http': 'http://10.10.1.10:3128',
  'http': 'http://10.10.1.10:1080',
}

Tags: 数据importiphttpurldataporttable
2条回答

我对它的两种看法

  1. 使用列表存储所有请求的URL

  2. 使用带有键http的dict,该键包含所有url的列表。

因此:

from bs4 import BeautifulSoup
import requests

data = []     # to store the urls in a list
dict_ = {}    # to store the urls in a dict as a list
proxy_url = 'https://free-proxy-list.net/'
req = requests.get(proxy_url)
soup = BeautifulSoup(req.content,'lxml')
table = soup.findAll('table')[0].findAll('tr')
for i in table:
    ip = i.select('td:nth-of-type(1)')
    port = i.select('td:nth-of-type(2)')

    if ip:
        ipx = ip[0].text

    if port:
        portx = port[0].text
        proxy = ('http//'+ipx+':'+portx)
        data.append(proxy)

dict_.update({'http':data})

print("List of urls: {}".format(data))
print("Dict of urls: {}".format(dict_))

输出

List of urls: ['http//223.25.101.242:59504', 'http//36.89.183.77:61612', . . .]
Dict of urls: {'http': ['http//223.25.101.242:59504', 'http//36.89.183.77:61612', . . .]}

python字典不会有一个具有多个值的键。 相反,您可能需要一个列表来保存这些值集。例如,您可以这样做:

data = {
  'http': ['http://10.10.1.10:3128', 'http://10.10.1.10:1080']
}

假设你想把偶数和奇数存储到100。你可以做:

output = {'even':[],'odd':[]}
for number in range(0,100):
    if number%2==0:
        output['even'].append(number)
    else:
        output['odd'].append(number)

相关问题 更多 >