How to print a dictionary's key?

前端 未结 20 831
眼角桃花
眼角桃花 2020-11-27 09:22

I would like to print a specific Python dictionary key:

mydic = {}
mydic[\'key_name\'] = \'value_name\'

Now I can check if mydic.has_

20条回答
  •  庸人自扰
    2020-11-27 09:43

    I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.


    Background

    I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).

    Find keys for given values

    The following code correctly finds my keys, given values:

    def k4v_edited(my_dict, value):
        values_list = []
        for k, v in my_dict.items():
            if v == value:
                values_list.append(k)
        return values_list
    
    print(k4v_edited(edge_attributes, '5.3.1.9'))
    ## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]
    

    whereas this code returns only the first (of possibly several matching) keys:

    def k4v(my_dict, value):
        for k, v in my_dict.items():
            if v == value:
                return k
    
    print(k4v(edge_attributes, '5.3.1.9'))
    ## (604, 1037, 0)
    
    

    The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.

提交回复
热议问题