2014-05-12 125 views
2

我有字典的字典。我希望有一个功能,如果arguement就像是匹配的将返回所有的细节,Python中的字典的字典的迭代字典

identifiers = { 
    '42566431313931326462642d3533656132352033': {   
     'name': 'topleft',   
     'subid': { 
      'a3e54b84450000': { 
       'name': 'north'     
      } 
     }   
    }, 
    '0942378098093': {   
     'name': 'topright',   
     'subid': { 
      '4b840000100000000000': { 
       'name': 'north'     
      } 
     }   
    }, 
    '4256643131ra98892389': {   
     'name': 'bottomleft',   
     'subid': { 
      'a3e54b840000100000000000': { 
       'name': 'west'     
      } 
     }   
    } 
} 

def getdetails(p): 
    # p could be key of dict or dict of dict 
    for key in identifiers: 
     if key == p: 
      return identifiers[key]   
     else: 
      if p in identifiers[key]['subid']: 
       return identifiers[key]['subid'][p] 

我想知道是否有高贵的方式来做到这一点(可以是使用地图和lambda)?

+0

什么是'D',为什么你覆盖'key'? – thefourtheye

+0

'identifier'与'identifiers'不同吗? – thefourtheye

+0

提示:在Python中使用'//'注释会引发语法错误 –

回答

5

可读性很重要。当你的代码是可读的,我会稍微提高了代码,这样

def getdetails(p): 
    if p in ids: 
     return ids[p] 

    for k, v in ids.iteritems(): 
     if p in v['subid']: 
      return v['subid'][p] 

但是,如果你正在寻找一个俏皮话,您可以创建一个生成器表达式,返回的第一个值从了。

def getdetails(p): 
    if p in ids: return ids[p] 
    return next(v['subid'][p] for k, v in ids.iteritems() if p in v['subid']) 

可以进一步缩短代码,这样

def getdetails(p): 
    return ids.get(p) or next(v['subid'][p] for k, v in ids.iteritems() if p in v['subid']) 

dict.get将返回None如果该键没有在字典中找到,并且被认为是Falsy在Python。所以,如果它不在主词典中,我们将检查子词典。

如果您正在使用Python 3.x中,你需要使用的,而不是iteritemsitems方法,这样

def getdetails(p): 
    return ids.get(p) or next(v['subid'][p] for k, v in ids.items() if p in v['subid']) 
+0

@Pilot'a3e54b840000100000000000'应该输出什么? – thefourtheye

+0

@Pilot但有两个项目匹配相同的ID。 “北”和“西”。你确定你只想要'西'吗? – thefourtheye

+0

@Pilot请检查最新的答案。 – thefourtheye

2
for key,value in identifiers.items(): 
     if key == p: 
      return identifiers[key]   
     else: 
      if p in identifiers[key]['subid']: 
       return identifiers[key]['subid'][p] 
2

如果您确定p在里面subid如果不是在顶层可以是这样的下面也会起作用。

def getdetails(p): 
    req_val = identifiers.get(p) 
    if not req_val: 
     for key, value in identifiers.items(): 
      req_val = value['subid'].get(p) 
    return req_val 
2

尝试递归这样的:

def getdetails(p, dictionary): 
    result = [] 
    if type(dictionary) is not dict: 
     return result 
    for key in dictionary: 
     if key == p: 
      result.append(dictionary[p]) 
     result += getdetails(p, dictionary[key]) 

    return result 

print getdetails('name', identifiers) 
print getdetails('subid', identifiers)