How to print a dictionary's key?

前端 未结 20 725
眼角桃花
眼角桃花 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:37

    If you want to get the key of a single value, the following would help:

    def get_key(b): # the value is passed to the function
        for k, v in mydic.items():
            if v.lower() == b.lower():
                return k
    

    In pythonic way:

    c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
         "Enter a valid 'Value'")
    print(c)
    
    0 讨论(0)
  • 2020-11-27 09:38
    import pprint
    pprint.pprint(mydic.keys())
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 09:45

    Probably the quickest way to retrieve only the key name:

    mydic = {}
    mydic['key_name'] = 'value_name'
    
    print mydic.items()[0][0]
    

    Result:

    key_name
    

    Converts the dictionary into a list then it lists the first element which is the whole dict then it lists the first value of that element which is: key_name

    0 讨论(0)
  • 2020-11-27 09:48

    Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?

    def key_for_value(d, value):
        """Return a key in `d` having a value of `value`."""
        for k, v in d.iteritems():
            if v == value:
                return k
    

    Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.

    If you need to do this frequently, it would make sense to construct the reverse dictionary:

    d_rev = dict(v,k for k,v in d.iteritems())
    
    0 讨论(0)
  • dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
    
    # Choose key to print (could be a user input)
    x = 'name'
    
    if x in dict.keys():
        print(x)
    
    0 讨论(0)
提交回复
热议问题