Python词典,找到相似之处

时间:2011-01-25 18:40:09

标签: python templates dictionary templating

我有一个包含一千个项目的python字典。每个项目本身就是一本字典。我正在寻找一种干净而优雅的方式来解析每个项目,并找到&创建模板。

以下是单个词典结构的简化示例:

{'id': 1,
 'template': None,
 'height': 80,
 'width': 120,
 'length': 75,
 'weight': 100}

由此,我想要传递一次,如果1000中的500个共享相同的高度和宽度,请确定,因此我可以从该数据构建模板,并将模板ID分配给“模板”。我可以建立一个巨大的参考哈希,但我希望有一个更清洁,更优雅的方式来实现这一目标。

实际数据包括更接近30个密钥,其中一小部分需要从模板检查中排除。

2 个答案:

答案 0 :(得分:3)

鉴于dicts的字典items

import itertools as it

for (height, width), itemIter in it.groupby (items.values(), lambda x: (x['height'], x['width'])):
    # in list(itemIter) you will find all items with dimensions (height, width)

答案 1 :(得分:0)

@eumiro有一个很好的核心理念,即使用itertools.groupby()分批排列具有共同值的项目。然而,除了忽略使用与@Jochen Ritzel指出的相同的键功能(并且在文档中也提到)首先对事物进行排序之外,他还没有解决您提到的其他几个想要做的事情。

下面是一个更完整,更长的答案。它决定了模板,并在一次通过中将它们分配给思想字典。为此,在首次创建已排序的项目列表后,它会使用groupby()对其进行批处理,如果每个组中有足够的项目,则创建一个模板并将其ID分配给每个成员。

inventory = {
    'item1': {'id': 1, 'template': None, 'height': 80, 'width': 120, 'length': 75, 'weight': 100},
    'item2': {'id': 2, 'template': None, 'height': 30, 'width': 40,  'length': 20, 'weight': 20},
    'item3': {'id': 3, 'template': None, 'height': 80, 'width': 100, 'length': 96, 'weight': 150},
    'item4': {'id': 4, 'template': None, 'height': 30, 'width': 40,  'length': 60, 'weight': 75},
    'item5': {'id': 5, 'template': None, 'height': 80, 'width': 100, 'length': 36, 'weight': 33}
}

import itertools as itools

def print_inventory():
    print 'inventory:'
    for key in sorted(inventory.iterkeys()):
        print '  {}: {}'.format(key, inventory[key])

print "-- BEFORE --"
print_inventory()

THRESHOLD = 2
ALLKEYS = ['template', 'height', 'width', 'length', 'weight']
EXCLUDEDKEYS = ['template', 'length', 'weight']
INCLUDEDKEYS = [key for key in ALLKEYS if key not in EXCLUDEDKEYS]

# determines which keys make up a template
sortby = lambda item, keys=INCLUDEDKEYS: tuple(item[key] for key in keys)

templates = {}
templateID = 0
sortedinventory = sorted(inventory.itervalues(), key=sortby)
for templatetuple, similariter in itools.groupby(sortedinventory, sortby):
    similaritems = list(similariter)
    if len(similaritems) >= THRESHOLD:
        # create and assign a template
        templateID += 1
        templates[templateID] = templatetuple # tuple of values of INCLUDEDKEYS
        for item in similaritems:
            item['template'] = templateID
print
print "-- AFTER --"
print_inventory()
print
print 'templates:', templates
print

当我运行它时,输出如下:

-- BEFORE --
inventory:
  item1: {'weight': 100, 'height': 80, 'width': 120, 'length': 75, 'template': None, 'id': 1}
  item2: {'weight': 20, 'height': 30, 'width': 40, 'length': 20, 'template': None, 'id': 2}
  item3: {'weight': 150, 'height': 80, 'width': 100, 'length': 96, 'template': None, 'id': 3}
  item4: {'weight': 75, 'height': 30, 'width': 40, 'length': 60, 'template': None, 'id': 4}
  item5: {'weight': 33, 'height': 80, 'width': 100, 'length': 36, 'template': None, 'id': 5}

-- AFTER --
inventory:
  item1: {'weight': 100, 'height': 80, 'width': 120, 'length': 75, 'template': None, 'id': 1}
  item2: {'weight': 20, 'height': 30, 'width': 40, 'length': 20, 'template': 1, 'id': 2}
  item3: {'weight': 150, 'height': 80, 'width': 100, 'length': 96, 'template': 2, 'id': 3}
  item4: {'weight': 75, 'height': 30, 'width': 40, 'length': 60, 'template': 1, 'id': 4}
  item5: {'weight': 33, 'height': 80, 'width': 100, 'length': 36, 'template': 2, 'id': 5}

templates: {1: (30, 40), 2: (80, 100)}