词典字典,获取值的共同关键字

时间:2014-07-24 13:56:43

标签: python dictionary key return-value

我有一本很大的字典词典,就像这样:

Dict={,
    ...
    '25465466':{'Cmstrk': 'cms_trk_dcs_05:CAEN', 'Crate': 'easyCrate0', 'Board': 'easyBoard06', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_4', 'Channel': 'channel003\n'},
    '436232302': {'Cmstrk': 'cms_trk_dcs_03:CAEN', 'Crate': 'easyCrate1', 'Board': 'easyBoard01', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_8', 'Channel': 'channel002\n'},
    '470311412': {'Cmstrk': 'cms_trk_dcs_03:CAEN', 'Crate': 'easyCrate0', 'Board': 'easyBoard00', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_4', 'Channel': 'channel003\n'},
    ...
} 

如果用户键入cms_trk_dcs_05:CAENeasyCrate1/easyBoard01或更多此值的组合,则脚本必须返回他们共有的那些键(例如' 654546536')。

例如,如果输入为easyCrate0/CMS_TRACKER_SY1527_4,则答案为470311412,25465466

3 个答案:

答案 0 :(得分:0)

我想这应该会有所帮助。

Dict = {
'25465466':{'Cmstrk': 'cms_trk_dcs_05:CAEN', 'Crate': 'easyCrate0', 'Board': 'easyBoard06', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_4', 'Channel': 'channel003\n'},

'436232302': {'Cmstrk': 'cms_trk_dcs_03:CAEN', 'Crate': 'easyCrate1', 'Board': 'easyBoard01', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_8', 'Channel': 'channel002\n'},

'470311412': {'Cmstrk': 'cms_trk_dcs_03:CAEN', 'Crate': 'easyCrate0', 'Board': 'easyBoard00', 'Branch': 'branchController05', 'TrackerSY': 'CMS_TRACKER_SY1527_4', 'Channel': 'channel003\n'}
}

def sub_search(terms):
    check = lambda k: all(map(lambda term:term in Dict[k].values(), terms))
    return [key for key,value in Dict.items() if check(key)]

def search(term):
    terms = term.split('/')
    return sub_search(terms)

search('cms_trk_dcs_05:CAEN')
#['25465466']

search('easyCrate1/easyBoard01')
#['436232302']

答案 1 :(得分:0)

inp = "easyCrate0/CMS_TRACKER_SY1527_4".split("/")
common = []
for k in Dict:
    if all(x in Dict[k].values() for x in inp): # if all of the values match the user input, add it to common list
        common.append(k) 
print (common)
['25465466', '470311412']

你也可以使用套装:

common = []
for k in Dict:
    if len(set(inp).intersection(Dict[k].values())) == len(inp):
        common.append(k)

您也可以使用列表组合:

common = [k  for k in Dict if len(set(inp).intersection(Dict[k].values())) == len(inp)]

答案 2 :(得分:0)

最终编辑: 这是代码清理程序:

from collections import OrderedDict

find = raw_input("What are you looking for? ")
finder = find.split('/')

similar = []
for key in Dict:
    for x in range(0, len(finder)):
        for pairs in Dict[key].items():
            if pairs[1] == finder[0]: 
                similar.append(key)

if len(similar) == 1 or len(finder) == 1:
    print ",".join(similar) 
for items in similar:
    similar.remove(items)
print ",".join(list(OrderedDict.fromkeys(similar)))