MathiasOrtner
MathiasOrtner

Reputation: 583

Pythonic way to get the index of element from a list of dicts depending on multiple keys

I am very new to python, and I have the following problem. I came up with the following solution. I am wondering whether it is "pythonic" or not. If not, what would be the best solution ?

The problem is :

This is my python example

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

Upvotes: 0

Views: 76

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279325

Looks reasonable to me, but perhaps a little too much. You could instead do:

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

Then access it with mapping['NA', 'GA', 'FA'] instead of mapping['NA']['GA']['FA']. But it really depends how you're planning to use the mapping. If you need to be able to take mapping['NA'] and use it as a dictionary then what you have is fine.

Upvotes: 1

Related Questions