Group By Python Dictionary中的值

时间:2017-12-16 15:32:03

标签: python-3.x dictionary

字典包含数组中的块值,我必须按'块'分组并使用字典法获取最小的键,即使用字符的ASCII值并附加到列表中。例如,如果我们采用块值[502698,5067024],那么BAYMON:6680:2键应该附加在列表中,而块[501930,5025121]键GREYHORN:6679:2应该被列在列表中,因为这是最小的。

dict= 
    { 
            'BAYMON:6680:2': {'blocks': [502698, 5067024], 'cnt': 2}
            'GREYHORN:6679:2': {'blocks': [501930, 5025121], 'cnt': 2}
            'GREYHORN:6681:2': {'blocks': [501930, 5025121], 'cnt': 2}
            'GREYHORN:6680:2' :{'blocks': [501930, 5025121], 'cnt': 2}
            'GREYHORN:6679:2' : {'blocks': [501930, 5025121], 'cnt': 2}
            'BAYMON:6681:2' :{'blocks': [502698, 5067024], 'cnt': 2}
    }

list = ['BAYMON:6680:2','GREYHORN:6679:2']

1 个答案:

答案 0 :(得分:1)

这是一个非加密的解决方案。

def smallest_key_by_blocks( dictio ) : 
    # mapping of blocks -> key 
    # will key the smallest key for each blocks
    smallest_dict = {}  

    for key, val in dictio.items() : 
        #convert to tuple so that we can use this as a key in dictionary
        blocks = tuple( val['blocks'] ) 

        if blocks not in smallest_dict : 
            # if no key seen so far for these blocks
            smallest_dict[ blocks ] = key 
        else : 
            # possibly update if the key is smaller 
            smallest_dict[ blocks ] = min( smallest_dict[blocks], key ) 

    return list( smallest_dict.values() )

在字典上使用.get方法的解决方案略为简洁...

def smallest_key_by_blocks_v1( dictio ) :         
    # mapping of blocks -> key 
    # will key the smallest key for each blocks
    smallest_dict = {}      
    for key, val in dictio.items() : 
        #convert to tuple so that we can use this as a key in dictionary
        blocks = tuple( val['blocks'] ) 
        key_sofar =  smallest_dict.get(blocks,key)
        smallest_dict[ blocks ] = min( key_sofar , key ) 

    return list( smallest_dict.values() )

更简洁,也许更清晰...:

def smallest_key_by_blocks_v2( dictio ) :         
    # first sort tuples of the form (key, blocks) 
    # then traverse and build the dictionary
    # .setdefault method guarantees that only the first key in the 
    # order will be assigned to blocks
    smallest_dict = {}
    sorted_tups = sorted( ( key, tuple(rec['blocks'])) 
                          for key, rec in dictio.items()   )
    for key, blocks in sorted_tups :
        smallest_dict.setdefault( blocks, key ) 

    return list( smallest_dict.values() )