Pythonic方法从取决于多个键的dicts列表中获取元素的索引

时间:2015-03-12 16:00:10

标签: python list dictionary

我是python的新手,我有以下问题。我提出了以下解决方案。我想知道它是否是“pythonic”。如果没有,那么最佳解决方案是什么?

问题是:

  • 我有一个dict列表
  • 每个词典至少有三个项目
  • 我想找到具有特定三个值的字典列表中的位置

这是我的python示例

import collections
import random

# lets build the list, for the example 
dicts = [] 
dicts.append({'idName':'NA','idGroup':'GA','idFamily':'FA'})
dicts.append({'idName':'NA','idGroup':'GA','idFamily':'FB'})
dicts.append({'idName':'NA','idGroup':'GB','idFamily':'FA'})
dicts.append({'idName':'NA','idGroup':'GB','idFamily':'FB'})
dicts.append({'idName':'NB','idGroup':'GA','idFamily':'FA'})
dicts.append({'idName':'NB','idGroup':'GA','idFamily':'FB'})
dicts.append({'idName':'NB','idGroup':'GB','idFamily':'FA'})
dicts.append({'idName':'NB','idGroup':'GB','idFamily':'FB'})


# let's shuffle it, again for example
random.shuffle(dicts)

# now I want to have for each combination the index 

# I use a recursive defaultdict definition 
# because it permits creating a dict of dict 
# even if it is not initialized 

def tree(): return collections.defaultdict(tree)

# initiate mapping 
mapping = tree()

# fill the mapping
for i,d  in enumerate(dicts):        

    idFamily = d['idFamily']
    idGroup = d['idGroup']
    idName = d['idName']

    mapping[idName][idGroup][idFamily] = i

# I end up with the mapping providing me with the index within 
# list of dicts

1 个答案:

答案 0 :(得分:1)

对我来说看起来很合理,但也许有点太多了。你可以这样做:

mapping = {
    (d['idName'], d['idGroup'], d['idFamily']) : i
    for i, d in enumerate(dicts)
}

然后使用mapping['NA', 'GA', 'FA']代替mapping['NA']['GA']['FA']访问它。但这实际上取决于您计划如何使用mapping。如果您需要能够使用mapping['NA']并将其用作字典,那么您所拥有的就可以了。