简体   繁体   中英

Accessing python dictionary whose keys are tuples with a wildcard

I have a dictionary with tuples as keys:

d = {
    ('John', 'Blue', 1): 100,
    ('Bill', 'Green', 5): 200,
    ('Paul', 'Blue', 4): 300,
    ('Bill', 'Green', 7): 400
}

Is it possible to pull out the values of those keys which match, say ('Bill', 'Green', _) , such that the output will be [200, 400] ?

Don't expect it to be very fast, but:

search_key = ("Paul", "Blue")
values = [value for key, value in d.items() if search_key == key[:len(search_key)]]

Will return all matching values.

EDIT: by replacing key[:2] with key[:len(search_key)] this solution also works with keys with only one value, eg ("Bill",) will return all values with keys starting with "Bill".

Using list comprehension:

[d[k] for k in d.keys() if k[0]=='Bill' and k[1]=='Green']
Out[37]: [400, 200]

A python dictionary is implemented as a hash table so there is no efficient way to find similar keys, only exact matches. You can of course loop over the items and check each key to see if it matches your pattern.

Python does have a groupby function which might be helpful if you're looking for multiple matches, for example:

from itertools import groupby

d = {
    ('John', 'Blue', 1): 100,
    ('Bill', 'Green', 5): 200,
    ('Paul', 'Blue', 4): 300,
    ('Bill', 'Green', 7): 400
}

keyfunc = lambda (key, value): (key[0], key[1])
g = sorted(d.items(), key=keyfunc)
g = groupby(g, key=keyfunc)

for (partial_key, value) in g:
    print partial_key, len(list(value))
# ('Bill', 'Green') 2
# ('John', 'Blue') 1
# ('Paul', 'Blue') 1

MaThMaX遵循的路径的变体

[d[(a,b,c)] for a, b, c in d.keys() if a == 'Bill' and b == 'Green']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM