简体   繁体   English

访问其关键字是带通配符的元组的python字典

[英]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] ? 是否可以拉出匹配的键值,例如('Bill', 'Green', _) ,这样输出将为[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". 编辑:通过将key[:2]替换为key[:len(search_key)]该解决方案也可用于只有一个值的键,例如("Bill",)将返回所有以“ 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. python字典被实现为哈希表,因此没有有效的方法来找到相似的键,只有完全匹配。 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: Python确实具有groupby函数,如果您要查找多个匹配项,则可能会有所帮助,例如:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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