我有一本字典,
dct = {'slab1': {'name':'myn1', 'age':20}, 'slab2':{'name':'myn2','age':200}}
lst = {'/store/dir1/dir_slab1/tindy', '/store/dir2/dirslab2_fine/tunka','/store/dir1/dirslab3/lunku'}
如何搜索列表元素中字典键的'slab1','slab2'?如果有匹配,我想打印匹配的元素和字典中的'age'。所以,在上面的例子中,我应该得到类似的东西:
'/store/dir1/dir_slab1/tindy', 20
'/store/dir2/dirslab2_fine/tunka', 200
感谢您的任何建议
答案 0 :(得分:0)
>>> dct = {'slab1': {'name':'myn1', 'age':20}, 'slab2':{'name':'myn2','age':200}}
>>> lst = {'/store/dir1/dir_slab1/tindy', '/store/dir2/dirslab2_fine/tunka','/store/dir1/dirslab3/lunku'}
>>> for item in lst:
... for pattern in dct:
... if pattern in item:
... print "%s, %s" % (item, dct[pattern]["age"])
...
/store/dir1/dir_slab1/tindy, 20
/store/dir2/dirslab2_fine/tunka, 200
您还可以使用列表理解符号来获取对:
>>> [(item, dct[pattern]["age"]) for item in lst for pattern in dct if pattern in item]
[('/store/dir1/dir_slab1/tindy', 20), ('/store/dir2/dirslab2_fine/tunka', 200)]
P.S。您的问题中存在一些误解(例如,list
变量不是列表),但解决方案应如下所示。