【发布时间】:2015-05-17 08:51:25
【问题描述】:
我正在尝试将一个大字典拆分为 n 个较小的字典。每个字典条目都包含一个网址,拆分字典的目的是让这些地址的网页抓取可以分布在多台计算机上。
字典格式为:
{
u'25637293':
[u'Methyldopa',u'http://www.ncbi.nlm.nih.gov/pubmed/25637293', 43579],
u'25672666':
[u'Furosemide', u'http://www.ncbi.nlm.nih.gov/pubmed/25672666', 40750]
}
包含 13000 个键/值对。
值中的最后一项是从 0 到 13000 的索引
这是我尝试过的。 (虽然我可能把事情复杂化了)
1) 创建一个包含 13000 个值的列表
2) 将其拆分为 n 个数量
3) 确保字典有 1-13000 的条目
4) 遍历列表。 if (i in list == the entry of dictionary) then the web address can be extracted for scraping(代码中没有最后一部分)
smalldict={}
#create a list from 0-13000 and split it into dictionaries of n number
def chunks(l, n):
n = max(1, n)
return [l[i:i + n] for i in range(0, len(l), n)]
#here I am inserting the values for the number of computers and how many dictionaries the big dictionary needs to be divided into
number = len(dictionary)
#entry for the number of dictionaries to divide it into
computers =4
#this is the 'name' of the computer that is running the script
compno = 1
#-1 because of 0 indexing
compm=compno-1
listlength = number/computers
divider= range(number)
division = chunks(divider, listlength)
for entry in dictionary:
#get all of the values from the value
value=dictionary[entry]
#specify the smaller dictionary that will be created
for i in division[compm]:
#if the number up to 13000 is in the dictionary
if i == value[2]
smalldict[value[1]]=value
我原以为 len(smalldict) 会是 13000/4(因为 len(dictionary) 是 13000,而 len(division[0]) 当分区中只有一个列表时)但它只返回几百个。它没有像它应该的那样分裂。
我已经为此工作了很多天。有人可以帮忙吗?
【问题讨论】:
-
听起来你需要一个数据库。我建议您阅读有关SQLite 的信息。虽然它不是您唯一的选择,但与 Python 一起使用非常简单。
-
我对上一节的逻辑有点困惑。您只是想将字典任意分成大小相等的块,还是对哪些项目进入哪些块有额外的限制?
-
我正在尝试将字典分成大致相等的块 - 对于哪些项目进入哪些块没有限制。
标签: python dictionary split divide chunking