【问题标题】:How do I split a dictionary into specific number of smaller dictionaries using python?如何使用 python 将字典拆分为特定数量的较小字典?
【发布时间】: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


【解决方案1】:

这个要点对我有用:https://gist.github.com/miloir/2196917

我用itertools.cycle 重写了它。

import itertools
def split_dict(x, chunks):      
    i = itertools.cycle(range(chunks))       
    split = [dict() for _ in range(chunks)]
    for k, v in x.items():
        split[next(i)][k] = v
    return split

【讨论】:

    【解决方案2】:

    简单。这样做。例如,我们有一个包含五个键的字典,我们想将它分成两个大小相等的字典。

    >>> d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
    >>> d1 = dict(d.items()[len(d)/2:])
    >>> d2 = dict(d.items()[:len(d)/2])
    >>> print d1
    {'key1': 1, 'key5': 5, 'key4': 4}
    >>> print d2
    {'key3': 3, 'key2': 2}
    

    【讨论】:

    • 这对我不起作用,但我更喜欢这个想法而不是选择的答案。我的修改版本: d1 = {k:d[k] for k in list(d.keys())[:int(len(d)*0.5)]}
    猜你喜欢
    • 2015-03-10
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2014-05-17
    相关资源
    最近更新 更多