Matthew The Terrible
Matthew The Terrible

Reputation: 1643

List of tuples of dictionaries and ints, how to search through each dict

I'm working on a project in which I have a list that contains tuples of a dict and an int. I'm trying to search through each dictionary for a give name but I'm having some trouble.

dicts = [ (somedict, 0), (someOtherDict, 5)]

Before I just had a list of dicts so I could easily search through with

def search(name):
    for d in reversed(dicts):
        if name in d: return d[name]

But now that I have a list of tuples I'm not quite sure how to search through the dictionaries. Any help or advice would be greatly appreciated. I'm so confused now.

Upvotes: 1

Views: 103

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123480

Just use a generator expression to get your dicts:

def search(name):
    for d in (t[0] for t in dicts):
        if name in d: return d[name]

Alternatively you can use tuple assignment:

def search(name):
    for d, _ in dicts:
        if name in d: return d[name]

but that assumes that all your tuples have 2 values.

Upvotes: 3

AlexanderBrevig
AlexanderBrevig

Reputation: 1987

You'll need to index the results from enumerating dicts with 0 because that's where your dict is in the dict/int tuple.

def search(name):
    for d in reversed(dicts):
        if name in d[0]: return d[0][name]

Upvotes: 0

Related Questions