How to print a dictionary's key?










161















I would like to print a specific Python dictionary key:



mydic = 
mydic['key_name'] = 'value_name'


Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):



print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']


Is there any name_the_key() method to print a key name?




Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)










share|improve this question



















  • 17





    If you know what the specific key you want is, umm, you already know what the key is.

    – Wooble
    May 5 '11 at 22:52






  • 27





    It's not nice to down vote just because the answer may be obvious to you.

    – zenna
    May 5 '11 at 22:55






  • 4





    @zenna: still one year after I kind of smirk at my own question :)

    – Benjamin
    May 24 '12 at 19:10






  • 5





    @Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

    – Mike S
    Sep 15 '15 at 14:01












  • @MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

    – Benjamin
    Sep 27 '15 at 6:17















161















I would like to print a specific Python dictionary key:



mydic = 
mydic['key_name'] = 'value_name'


Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):



print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']


Is there any name_the_key() method to print a key name?




Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)










share|improve this question



















  • 17





    If you know what the specific key you want is, umm, you already know what the key is.

    – Wooble
    May 5 '11 at 22:52






  • 27





    It's not nice to down vote just because the answer may be obvious to you.

    – zenna
    May 5 '11 at 22:55






  • 4





    @zenna: still one year after I kind of smirk at my own question :)

    – Benjamin
    May 24 '12 at 19:10






  • 5





    @Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

    – Mike S
    Sep 15 '15 at 14:01












  • @MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

    – Benjamin
    Sep 27 '15 at 6:17













161












161








161


48






I would like to print a specific Python dictionary key:



mydic = 
mydic['key_name'] = 'value_name'


Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):



print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']


Is there any name_the_key() method to print a key name?




Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)










share|improve this question
















I would like to print a specific Python dictionary key:



mydic = 
mydic['key_name'] = 'value_name'


Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):



print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']


Is there any name_the_key() method to print a key name?




Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the 'key_name' to refer to the key! :)







python dictionary key






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 27 '18 at 22:23









codeforester

18.3k84267




18.3k84267










asked May 5 '11 at 22:51









BenjaminBenjamin

2,14363165




2,14363165







  • 17





    If you know what the specific key you want is, umm, you already know what the key is.

    – Wooble
    May 5 '11 at 22:52






  • 27





    It's not nice to down vote just because the answer may be obvious to you.

    – zenna
    May 5 '11 at 22:55






  • 4





    @zenna: still one year after I kind of smirk at my own question :)

    – Benjamin
    May 24 '12 at 19:10






  • 5





    @Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

    – Mike S
    Sep 15 '15 at 14:01












  • @MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

    – Benjamin
    Sep 27 '15 at 6:17












  • 17





    If you know what the specific key you want is, umm, you already know what the key is.

    – Wooble
    May 5 '11 at 22:52






  • 27





    It's not nice to down vote just because the answer may be obvious to you.

    – zenna
    May 5 '11 at 22:55






  • 4





    @zenna: still one year after I kind of smirk at my own question :)

    – Benjamin
    May 24 '12 at 19:10






  • 5





    @Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

    – Mike S
    Sep 15 '15 at 14:01












  • @MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

    – Benjamin
    Sep 27 '15 at 6:17







17




17





If you know what the specific key you want is, umm, you already know what the key is.

– Wooble
May 5 '11 at 22:52





If you know what the specific key you want is, umm, you already know what the key is.

– Wooble
May 5 '11 at 22:52




27




27





It's not nice to down vote just because the answer may be obvious to you.

– zenna
May 5 '11 at 22:55





It's not nice to down vote just because the answer may be obvious to you.

– zenna
May 5 '11 at 22:55




4




4





@zenna: still one year after I kind of smirk at my own question :)

– Benjamin
May 24 '12 at 19:10





@zenna: still one year after I kind of smirk at my own question :)

– Benjamin
May 24 '12 at 19:10




5




5





@Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

– Mike S
Sep 15 '15 at 14:01






@Benjamin: Which is why there is no such thing as a dumb question. It drove a smart answer (juanchopanza's) and now years later myriad Googlers are finding it and learning the basics of Python keys! :-)

– Mike S
Sep 15 '15 at 14:01














@MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

– Benjamin
Sep 27 '15 at 6:17





@MikeS good point, AND I just selected Juan's answer. In retrospective---as well as per vote count---it was the best.

– Benjamin
Sep 27 '15 at 6:17












18 Answers
18






active

oldest

votes


















295














A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so



for key, value in mydic.iteritems() :
print key, value


Python 3 version:



for key, value in mydic.items() :
print (key, value)


So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.






share|improve this answer

























  • Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

    – piperchester
    Mar 27 '13 at 21:18







  • 3





    @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

    – juanchopanza
    Mar 27 '13 at 22:59






  • 4





    .items() works in both 2.7 and 3.x.

    – Bibhas Debnath
    Feb 18 '14 at 12:40






  • 1





    @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

    – juanchopanza
    Feb 18 '14 at 13:08


















30














Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?



If so you want the following:



for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]


Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.






share|improve this answer




















  • 2





    the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

    – John La Rooy
    May 6 '11 at 0:17






  • 1





    This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

    – Ned Batchelder
    May 6 '11 at 0:58











  • For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

    – Dominic Santos
    May 6 '11 at 7:55


















30














Additionally you can use....



print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values





share|improve this answer






























    27














    dic = "key 1":"value 1","key b":"value b"

    #print the keys:
    for key in dic:
    print key

    #print the values:
    for value in dic.itervalues():
    print value

    #print key and values
    for key, value in dic.iteritems():
    print key, value


    Note:In Python 3, dic.iteritems() was renamed as dic.items()






    share|improve this answer
































      24














      The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.






      share|improve this answer






























        6














        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())





        share|improve this answer























        • Note (as above) that iteritems became simply 'items' in Python 3.

          – Mike
          Sep 24 '18 at 2:31


















        4














        Or you can do it that manner:



        for key in my_dict:
        print key, my_dict[key]





        share|improve this answer






























          2














          What's wrong with using 'key_name' instead, even if it is a variable?






          share|improve this answer























          • it seemed wrong: but it isn't :) thanks.

            – Benjamin
            May 6 '11 at 10:42


















          2














          import pprint
          pprint.pprint(mydic.keys())





          share|improve this answer























          • docs.python.org/2/library/pprint.html#pprint.pprint

            – RzR
            Jun 20 '15 at 13:01


















          2














          # highlighting how to use a named variable within a string:
          dict = 'a': 1, 'b': 2

          # simple method:
          print "a %(a)s" % dict
          print "b %(b)s" % dict

          # programmatic method:
          for key in dict:
          val = '%('+key+')s'
          print key, val % dict

          # yields:
          # a 1
          # b 2

          # using list comprehension
          print "n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

          # yields:
          # a: 1
          # b: 2





          share|improve this answer
































            1














            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)





            share|improve this answer






























              1














              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






              share|improve this answer























              • Why retrieve the value too though?

                – Martijn Pieters
                Jun 24 '17 at 12:32


















              1














              Make sure to do



              dictionary.keys()
              # rather than
              dictionary.keys





              share|improve this answer























              • 7 years later: this question is still alive and kicking :)

                – Benjamin
                May 17 '18 at 14:27











              • some questions age like wine ;)

                – Crt
                May 17 '18 at 15:20


















              1














              In Python 3:



              # A simple dictionary
              x = 'X':"yes", 'Y':"no", 'Z':"ok"

              # To print a specific key (for example key at index 1)
              print([key for key in x.keys()][1])

              # To print a specific value (for example value at index 1)
              print([value for value in x.values()][1])

              # To print a pair of a key with its value (for example pair at index 2)
              print(([key for key in x.keys()][2], [value for value in x.values()][2]))

              # To print a key and a different value (for example key at index 0 and value at index 1)
              print(([key for key in x.keys()][0], [value for value in x.values()][1]))

              # To print all keys and values concatenated together
              print(''.join(str(key) + '' + str(value) for key, value in x.items()))

              # To print all keys and values separated by commas
              print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

              # To print all pairs of (key, value) one at a time
              for e in range(len(x)):
              print(([key for key in x.keys()][e], [value for value in x.values()][e]))

              # To print all pairs (key, value) in a tuple
              print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))





              share|improve this answer






























                0














                Try this:



                def name_the_key(dict, key):
                return key, dict[key]

                mydict = 'key1':1, 'key2':2, 'key3':3

                key_name, value = name_the_key(mydict, 'key2')
                print 'KEY NAME: %s' % key_name
                print 'KEY VALUE: %s' % value





                share|improve this answer






























                  0














                  key_name = '...'
                  print "the key name is %s and its value is %s"%(key_name, mydic[key_name])





                  share|improve this answer






























                    0














                    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)





                    share|improve this answer






























                      0














                      I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:



                      dict1 = 'random_word': [1,2,3]
                      key_name = str([key for key in dict1]).strip("''")
                      print(key_name) # equal to 'random_word', type: string.





                      share|improve this answer





















                        protected by codeforester Oct 27 '18 at 22:22



                        Thank you for your interest in this question.
                        Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                        Would you like to answer one of these unanswered questions instead?














                        18 Answers
                        18






                        active

                        oldest

                        votes








                        18 Answers
                        18






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes









                        295














                        A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so



                        for key, value in mydic.iteritems() :
                        print key, value


                        Python 3 version:



                        for key, value in mydic.items() :
                        print (key, value)


                        So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.






                        share|improve this answer

























                        • Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                          – piperchester
                          Mar 27 '13 at 21:18







                        • 3





                          @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                          – juanchopanza
                          Mar 27 '13 at 22:59






                        • 4





                          .items() works in both 2.7 and 3.x.

                          – Bibhas Debnath
                          Feb 18 '14 at 12:40






                        • 1





                          @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                          – juanchopanza
                          Feb 18 '14 at 13:08















                        295














                        A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so



                        for key, value in mydic.iteritems() :
                        print key, value


                        Python 3 version:



                        for key, value in mydic.items() :
                        print (key, value)


                        So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.






                        share|improve this answer

























                        • Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                          – piperchester
                          Mar 27 '13 at 21:18







                        • 3





                          @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                          – juanchopanza
                          Mar 27 '13 at 22:59






                        • 4





                          .items() works in both 2.7 and 3.x.

                          – Bibhas Debnath
                          Feb 18 '14 at 12:40






                        • 1





                          @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                          – juanchopanza
                          Feb 18 '14 at 13:08













                        295












                        295








                        295







                        A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so



                        for key, value in mydic.iteritems() :
                        print key, value


                        Python 3 version:



                        for key, value in mydic.items() :
                        print (key, value)


                        So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.






                        share|improve this answer















                        A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so



                        for key, value in mydic.iteritems() :
                        print key, value


                        Python 3 version:



                        for key, value in mydic.items() :
                        print (key, value)


                        So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 27 '13 at 22:58

























                        answered May 5 '11 at 23:21









                        juanchopanzajuanchopanza

                        190k21301412




                        190k21301412












                        • Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                          – piperchester
                          Mar 27 '13 at 21:18







                        • 3





                          @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                          – juanchopanza
                          Mar 27 '13 at 22:59






                        • 4





                          .items() works in both 2.7 and 3.x.

                          – Bibhas Debnath
                          Feb 18 '14 at 12:40






                        • 1





                          @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                          – juanchopanza
                          Feb 18 '14 at 13:08

















                        • Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                          – piperchester
                          Mar 27 '13 at 21:18







                        • 3





                          @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                          – juanchopanza
                          Mar 27 '13 at 22:59






                        • 4





                          .items() works in both 2.7 and 3.x.

                          – Bibhas Debnath
                          Feb 18 '14 at 12:40






                        • 1





                          @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                          – juanchopanza
                          Feb 18 '14 at 13:08
















                        Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                        – piperchester
                        Mar 27 '13 at 21:18






                        Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know .iteritems() is no longer supported...

                        – piperchester
                        Mar 27 '13 at 21:18





                        3




                        3





                        @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                        – juanchopanza
                        Mar 27 '13 at 22:59





                        @PolyShell the alternative in python 3, if that is what you mean by Py3k (I've been away from python for a while now) it .items(). I added an example.

                        – juanchopanza
                        Mar 27 '13 at 22:59




                        4




                        4





                        .items() works in both 2.7 and 3.x.

                        – Bibhas Debnath
                        Feb 18 '14 at 12:40





                        .items() works in both 2.7 and 3.x.

                        – Bibhas Debnath
                        Feb 18 '14 at 12:40




                        1




                        1





                        @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                        – juanchopanza
                        Feb 18 '14 at 13:08





                        @Bibhas They both work, but the semantics are different. items() returns a list in python 2.x.

                        – juanchopanza
                        Feb 18 '14 at 13:08













                        30














                        Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?



                        If so you want the following:



                        for key in mydic:
                        print "the key name is" + key + "and its value is" + mydic[key]


                        Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.






                        share|improve this answer




















                        • 2





                          the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                          – John La Rooy
                          May 6 '11 at 0:17






                        • 1





                          This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                          – Ned Batchelder
                          May 6 '11 at 0:58











                        • For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                          – Dominic Santos
                          May 6 '11 at 7:55















                        30














                        Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?



                        If so you want the following:



                        for key in mydic:
                        print "the key name is" + key + "and its value is" + mydic[key]


                        Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.






                        share|improve this answer




















                        • 2





                          the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                          – John La Rooy
                          May 6 '11 at 0:17






                        • 1





                          This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                          – Ned Batchelder
                          May 6 '11 at 0:58











                        • For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                          – Dominic Santos
                          May 6 '11 at 7:55













                        30












                        30








                        30







                        Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?



                        If so you want the following:



                        for key in mydic:
                        print "the key name is" + key + "and its value is" + mydic[key]


                        Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.






                        share|improve this answer















                        Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?



                        If so you want the following:



                        for key in mydic:
                        print "the key name is" + key + "and its value is" + mydic[key]


                        Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jun 24 '17 at 12:31









                        Martijn Pieters

                        716k13825022315




                        716k13825022315










                        answered May 5 '11 at 23:07









                        Dominic SantosDominic Santos

                        1,5741013




                        1,5741013







                        • 2





                          the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                          – John La Rooy
                          May 6 '11 at 0:17






                        • 1





                          This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                          – Ned Batchelder
                          May 6 '11 at 0:58











                        • For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                          – Dominic Santos
                          May 6 '11 at 7:55












                        • 2





                          the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                          – John La Rooy
                          May 6 '11 at 0:17






                        • 1





                          This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                          – Ned Batchelder
                          May 6 '11 at 0:58











                        • For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                          – Dominic Santos
                          May 6 '11 at 7:55







                        2




                        2





                        the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                        – John La Rooy
                        May 6 '11 at 0:17





                        the comma will leave them on the same line, but insert spaces between "is" and key etc. If you use + you need to put the extra padding in the strings. Also key and value are not necessarily string, in which case comma will use str(key) and str(value) whereas + will cause an error

                        – John La Rooy
                        May 6 '11 at 0:17




                        1




                        1





                        This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                        – Ned Batchelder
                        May 6 '11 at 0:58





                        This is the one answer I know isn't right, since the OP said, "I don't want all the keys listed."

                        – Ned Batchelder
                        May 6 '11 at 0:58













                        For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                        – Dominic Santos
                        May 6 '11 at 7:55





                        For some reason I thought otherwise for the comma; you are right on that one. I've also re-read the question, it seems we have both put 'all' in bold - my bad.

                        – Dominic Santos
                        May 6 '11 at 7:55











                        30














                        Additionally you can use....



                        print(dictionary.items()) #prints keys and values
                        print(dictionary.keys()) #prints keys
                        print(dictionary.values()) #prints values





                        share|improve this answer



























                          30














                          Additionally you can use....



                          print(dictionary.items()) #prints keys and values
                          print(dictionary.keys()) #prints keys
                          print(dictionary.values()) #prints values





                          share|improve this answer

























                            30












                            30








                            30







                            Additionally you can use....



                            print(dictionary.items()) #prints keys and values
                            print(dictionary.keys()) #prints keys
                            print(dictionary.values()) #prints values





                            share|improve this answer













                            Additionally you can use....



                            print(dictionary.items()) #prints keys and values
                            print(dictionary.keys()) #prints keys
                            print(dictionary.values()) #prints values






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 15 '17 at 9:47









                            MasonMason

                            42649




                            42649





















                                27














                                dic = "key 1":"value 1","key b":"value b"

                                #print the keys:
                                for key in dic:
                                print key

                                #print the values:
                                for value in dic.itervalues():
                                print value

                                #print key and values
                                for key, value in dic.iteritems():
                                print key, value


                                Note:In Python 3, dic.iteritems() was renamed as dic.items()






                                share|improve this answer





























                                  27














                                  dic = "key 1":"value 1","key b":"value b"

                                  #print the keys:
                                  for key in dic:
                                  print key

                                  #print the values:
                                  for value in dic.itervalues():
                                  print value

                                  #print key and values
                                  for key, value in dic.iteritems():
                                  print key, value


                                  Note:In Python 3, dic.iteritems() was renamed as dic.items()






                                  share|improve this answer



























                                    27












                                    27








                                    27







                                    dic = "key 1":"value 1","key b":"value b"

                                    #print the keys:
                                    for key in dic:
                                    print key

                                    #print the values:
                                    for value in dic.itervalues():
                                    print value

                                    #print key and values
                                    for key, value in dic.iteritems():
                                    print key, value


                                    Note:In Python 3, dic.iteritems() was renamed as dic.items()






                                    share|improve this answer















                                    dic = "key 1":"value 1","key b":"value b"

                                    #print the keys:
                                    for key in dic:
                                    print key

                                    #print the values:
                                    for value in dic.itervalues():
                                    print value

                                    #print key and values
                                    for key, value in dic.iteritems():
                                    print key, value


                                    Note:In Python 3, dic.iteritems() was renamed as dic.items()







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 18 '18 at 15:14









                                    kumsgs

                                    475413




                                    475413










                                    answered Dec 18 '12 at 21:38









                                    ademar111190ademar111190

                                    8,966106290




                                    8,966106290





















                                        24














                                        The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.






                                        share|improve this answer



























                                          24














                                          The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.






                                          share|improve this answer

























                                            24












                                            24








                                            24







                                            The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.






                                            share|improve this answer













                                            The name of the key 'key_name' is key_name, therefore print 'key_name' or whatever variable you have representing it.







                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered May 5 '11 at 22:53









                                            zennazenna

                                            4,40595297




                                            4,40595297





















                                                6














                                                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())





                                                share|improve this answer























                                                • Note (as above) that iteritems became simply 'items' in Python 3.

                                                  – Mike
                                                  Sep 24 '18 at 2:31















                                                6














                                                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())





                                                share|improve this answer























                                                • Note (as above) that iteritems became simply 'items' in Python 3.

                                                  – Mike
                                                  Sep 24 '18 at 2:31













                                                6












                                                6








                                                6







                                                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())





                                                share|improve this answer













                                                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())






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered May 6 '11 at 0:57









                                                Ned BatchelderNed Batchelder

                                                259k53447567




                                                259k53447567












                                                • Note (as above) that iteritems became simply 'items' in Python 3.

                                                  – Mike
                                                  Sep 24 '18 at 2:31

















                                                • Note (as above) that iteritems became simply 'items' in Python 3.

                                                  – Mike
                                                  Sep 24 '18 at 2:31
















                                                Note (as above) that iteritems became simply 'items' in Python 3.

                                                – Mike
                                                Sep 24 '18 at 2:31





                                                Note (as above) that iteritems became simply 'items' in Python 3.

                                                – Mike
                                                Sep 24 '18 at 2:31











                                                4














                                                Or you can do it that manner:



                                                for key in my_dict:
                                                print key, my_dict[key]





                                                share|improve this answer



























                                                  4














                                                  Or you can do it that manner:



                                                  for key in my_dict:
                                                  print key, my_dict[key]





                                                  share|improve this answer

























                                                    4












                                                    4








                                                    4







                                                    Or you can do it that manner:



                                                    for key in my_dict:
                                                    print key, my_dict[key]





                                                    share|improve this answer













                                                    Or you can do it that manner:



                                                    for key in my_dict:
                                                    print key, my_dict[key]






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Sep 29 '15 at 11:44









                                                    Eugene SoldatovEugene Soldatov

                                                    6,9281833




                                                    6,9281833





















                                                        2














                                                        What's wrong with using 'key_name' instead, even if it is a variable?






                                                        share|improve this answer























                                                        • it seemed wrong: but it isn't :) thanks.

                                                          – Benjamin
                                                          May 6 '11 at 10:42















                                                        2














                                                        What's wrong with using 'key_name' instead, even if it is a variable?






                                                        share|improve this answer























                                                        • it seemed wrong: but it isn't :) thanks.

                                                          – Benjamin
                                                          May 6 '11 at 10:42













                                                        2












                                                        2








                                                        2







                                                        What's wrong with using 'key_name' instead, even if it is a variable?






                                                        share|improve this answer













                                                        What's wrong with using 'key_name' instead, even if it is a variable?







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered May 5 '11 at 22:54









                                                        Ry-Ry-

                                                        169k40345362




                                                        169k40345362












                                                        • it seemed wrong: but it isn't :) thanks.

                                                          – Benjamin
                                                          May 6 '11 at 10:42

















                                                        • it seemed wrong: but it isn't :) thanks.

                                                          – Benjamin
                                                          May 6 '11 at 10:42
















                                                        it seemed wrong: but it isn't :) thanks.

                                                        – Benjamin
                                                        May 6 '11 at 10:42





                                                        it seemed wrong: but it isn't :) thanks.

                                                        – Benjamin
                                                        May 6 '11 at 10:42











                                                        2














                                                        import pprint
                                                        pprint.pprint(mydic.keys())





                                                        share|improve this answer























                                                        • docs.python.org/2/library/pprint.html#pprint.pprint

                                                          – RzR
                                                          Jun 20 '15 at 13:01















                                                        2














                                                        import pprint
                                                        pprint.pprint(mydic.keys())





                                                        share|improve this answer























                                                        • docs.python.org/2/library/pprint.html#pprint.pprint

                                                          – RzR
                                                          Jun 20 '15 at 13:01













                                                        2












                                                        2








                                                        2







                                                        import pprint
                                                        pprint.pprint(mydic.keys())





                                                        share|improve this answer













                                                        import pprint
                                                        pprint.pprint(mydic.keys())






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered May 6 '11 at 5:37









                                                        Matt JoinerMatt Joiner

                                                        56.4k75292462




                                                        56.4k75292462












                                                        • docs.python.org/2/library/pprint.html#pprint.pprint

                                                          – RzR
                                                          Jun 20 '15 at 13:01

















                                                        • docs.python.org/2/library/pprint.html#pprint.pprint

                                                          – RzR
                                                          Jun 20 '15 at 13:01
















                                                        docs.python.org/2/library/pprint.html#pprint.pprint

                                                        – RzR
                                                        Jun 20 '15 at 13:01





                                                        docs.python.org/2/library/pprint.html#pprint.pprint

                                                        – RzR
                                                        Jun 20 '15 at 13:01











                                                        2














                                                        # highlighting how to use a named variable within a string:
                                                        dict = 'a': 1, 'b': 2

                                                        # simple method:
                                                        print "a %(a)s" % dict
                                                        print "b %(b)s" % dict

                                                        # programmatic method:
                                                        for key in dict:
                                                        val = '%('+key+')s'
                                                        print key, val % dict

                                                        # yields:
                                                        # a 1
                                                        # b 2

                                                        # using list comprehension
                                                        print "n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

                                                        # yields:
                                                        # a: 1
                                                        # b: 2





                                                        share|improve this answer





























                                                          2














                                                          # highlighting how to use a named variable within a string:
                                                          dict = 'a': 1, 'b': 2

                                                          # simple method:
                                                          print "a %(a)s" % dict
                                                          print "b %(b)s" % dict

                                                          # programmatic method:
                                                          for key in dict:
                                                          val = '%('+key+')s'
                                                          print key, val % dict

                                                          # yields:
                                                          # a 1
                                                          # b 2

                                                          # using list comprehension
                                                          print "n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

                                                          # yields:
                                                          # a: 1
                                                          # b: 2





                                                          share|improve this answer



























                                                            2












                                                            2








                                                            2







                                                            # highlighting how to use a named variable within a string:
                                                            dict = 'a': 1, 'b': 2

                                                            # simple method:
                                                            print "a %(a)s" % dict
                                                            print "b %(b)s" % dict

                                                            # programmatic method:
                                                            for key in dict:
                                                            val = '%('+key+')s'
                                                            print key, val % dict

                                                            # yields:
                                                            # a 1
                                                            # b 2

                                                            # using list comprehension
                                                            print "n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

                                                            # yields:
                                                            # a: 1
                                                            # b: 2





                                                            share|improve this answer















                                                            # highlighting how to use a named variable within a string:
                                                            dict = 'a': 1, 'b': 2

                                                            # simple method:
                                                            print "a %(a)s" % dict
                                                            print "b %(b)s" % dict

                                                            # programmatic method:
                                                            for key in dict:
                                                            val = '%('+key+')s'
                                                            print key, val % dict

                                                            # yields:
                                                            # a 1
                                                            # b 2

                                                            # using list comprehension
                                                            print "n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

                                                            # yields:
                                                            # a: 1
                                                            # b: 2






                                                            share|improve this answer














                                                            share|improve this answer



                                                            share|improve this answer








                                                            edited Feb 22 '18 at 17:52









                                                            DeadChex

                                                            2,7292029




                                                            2,7292029










                                                            answered Dec 20 '12 at 13:58









                                                            Brian BruggemanBrian Bruggeman

                                                            2,12412030




                                                            2,12412030





















                                                                1














                                                                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)





                                                                share|improve this answer



























                                                                  1














                                                                  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)





                                                                  share|improve this answer

























                                                                    1












                                                                    1








                                                                    1







                                                                    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)





                                                                    share|improve this answer













                                                                    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)






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jun 17 '15 at 10:54









                                                                    Rob WilsonRob Wilson

                                                                    112




                                                                    112





















                                                                        1














                                                                        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






                                                                        share|improve this answer























                                                                        • Why retrieve the value too though?

                                                                          – Martijn Pieters
                                                                          Jun 24 '17 at 12:32















                                                                        1














                                                                        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






                                                                        share|improve this answer























                                                                        • Why retrieve the value too though?

                                                                          – Martijn Pieters
                                                                          Jun 24 '17 at 12:32













                                                                        1












                                                                        1








                                                                        1







                                                                        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






                                                                        share|improve this answer













                                                                        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







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Feb 8 '16 at 11:04









                                                                        Fekete SumérFekete Sumér

                                                                        191




                                                                        191












                                                                        • Why retrieve the value too though?

                                                                          – Martijn Pieters
                                                                          Jun 24 '17 at 12:32

















                                                                        • Why retrieve the value too though?

                                                                          – Martijn Pieters
                                                                          Jun 24 '17 at 12:32
















                                                                        Why retrieve the value too though?

                                                                        – Martijn Pieters
                                                                        Jun 24 '17 at 12:32





                                                                        Why retrieve the value too though?

                                                                        – Martijn Pieters
                                                                        Jun 24 '17 at 12:32











                                                                        1














                                                                        Make sure to do



                                                                        dictionary.keys()
                                                                        # rather than
                                                                        dictionary.keys





                                                                        share|improve this answer























                                                                        • 7 years later: this question is still alive and kicking :)

                                                                          – Benjamin
                                                                          May 17 '18 at 14:27











                                                                        • some questions age like wine ;)

                                                                          – Crt
                                                                          May 17 '18 at 15:20















                                                                        1














                                                                        Make sure to do



                                                                        dictionary.keys()
                                                                        # rather than
                                                                        dictionary.keys





                                                                        share|improve this answer























                                                                        • 7 years later: this question is still alive and kicking :)

                                                                          – Benjamin
                                                                          May 17 '18 at 14:27











                                                                        • some questions age like wine ;)

                                                                          – Crt
                                                                          May 17 '18 at 15:20













                                                                        1












                                                                        1








                                                                        1







                                                                        Make sure to do



                                                                        dictionary.keys()
                                                                        # rather than
                                                                        dictionary.keys





                                                                        share|improve this answer













                                                                        Make sure to do



                                                                        dictionary.keys()
                                                                        # rather than
                                                                        dictionary.keys






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered May 17 '18 at 14:25









                                                                        CrtCrt

                                                                        2,36322435




                                                                        2,36322435












                                                                        • 7 years later: this question is still alive and kicking :)

                                                                          – Benjamin
                                                                          May 17 '18 at 14:27











                                                                        • some questions age like wine ;)

                                                                          – Crt
                                                                          May 17 '18 at 15:20

















                                                                        • 7 years later: this question is still alive and kicking :)

                                                                          – Benjamin
                                                                          May 17 '18 at 14:27











                                                                        • some questions age like wine ;)

                                                                          – Crt
                                                                          May 17 '18 at 15:20
















                                                                        7 years later: this question is still alive and kicking :)

                                                                        – Benjamin
                                                                        May 17 '18 at 14:27





                                                                        7 years later: this question is still alive and kicking :)

                                                                        – Benjamin
                                                                        May 17 '18 at 14:27













                                                                        some questions age like wine ;)

                                                                        – Crt
                                                                        May 17 '18 at 15:20





                                                                        some questions age like wine ;)

                                                                        – Crt
                                                                        May 17 '18 at 15:20











                                                                        1














                                                                        In Python 3:



                                                                        # A simple dictionary
                                                                        x = 'X':"yes", 'Y':"no", 'Z':"ok"

                                                                        # To print a specific key (for example key at index 1)
                                                                        print([key for key in x.keys()][1])

                                                                        # To print a specific value (for example value at index 1)
                                                                        print([value for value in x.values()][1])

                                                                        # To print a pair of a key with its value (for example pair at index 2)
                                                                        print(([key for key in x.keys()][2], [value for value in x.values()][2]))

                                                                        # To print a key and a different value (for example key at index 0 and value at index 1)
                                                                        print(([key for key in x.keys()][0], [value for value in x.values()][1]))

                                                                        # To print all keys and values concatenated together
                                                                        print(''.join(str(key) + '' + str(value) for key, value in x.items()))

                                                                        # To print all keys and values separated by commas
                                                                        print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

                                                                        # To print all pairs of (key, value) one at a time
                                                                        for e in range(len(x)):
                                                                        print(([key for key in x.keys()][e], [value for value in x.values()][e]))

                                                                        # To print all pairs (key, value) in a tuple
                                                                        print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))





                                                                        share|improve this answer



























                                                                          1














                                                                          In Python 3:



                                                                          # A simple dictionary
                                                                          x = 'X':"yes", 'Y':"no", 'Z':"ok"

                                                                          # To print a specific key (for example key at index 1)
                                                                          print([key for key in x.keys()][1])

                                                                          # To print a specific value (for example value at index 1)
                                                                          print([value for value in x.values()][1])

                                                                          # To print a pair of a key with its value (for example pair at index 2)
                                                                          print(([key for key in x.keys()][2], [value for value in x.values()][2]))

                                                                          # To print a key and a different value (for example key at index 0 and value at index 1)
                                                                          print(([key for key in x.keys()][0], [value for value in x.values()][1]))

                                                                          # To print all keys and values concatenated together
                                                                          print(''.join(str(key) + '' + str(value) for key, value in x.items()))

                                                                          # To print all keys and values separated by commas
                                                                          print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

                                                                          # To print all pairs of (key, value) one at a time
                                                                          for e in range(len(x)):
                                                                          print(([key for key in x.keys()][e], [value for value in x.values()][e]))

                                                                          # To print all pairs (key, value) in a tuple
                                                                          print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))





                                                                          share|improve this answer

























                                                                            1












                                                                            1








                                                                            1







                                                                            In Python 3:



                                                                            # A simple dictionary
                                                                            x = 'X':"yes", 'Y':"no", 'Z':"ok"

                                                                            # To print a specific key (for example key at index 1)
                                                                            print([key for key in x.keys()][1])

                                                                            # To print a specific value (for example value at index 1)
                                                                            print([value for value in x.values()][1])

                                                                            # To print a pair of a key with its value (for example pair at index 2)
                                                                            print(([key for key in x.keys()][2], [value for value in x.values()][2]))

                                                                            # To print a key and a different value (for example key at index 0 and value at index 1)
                                                                            print(([key for key in x.keys()][0], [value for value in x.values()][1]))

                                                                            # To print all keys and values concatenated together
                                                                            print(''.join(str(key) + '' + str(value) for key, value in x.items()))

                                                                            # To print all keys and values separated by commas
                                                                            print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

                                                                            # To print all pairs of (key, value) one at a time
                                                                            for e in range(len(x)):
                                                                            print(([key for key in x.keys()][e], [value for value in x.values()][e]))

                                                                            # To print all pairs (key, value) in a tuple
                                                                            print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))





                                                                            share|improve this answer













                                                                            In Python 3:



                                                                            # A simple dictionary
                                                                            x = 'X':"yes", 'Y':"no", 'Z':"ok"

                                                                            # To print a specific key (for example key at index 1)
                                                                            print([key for key in x.keys()][1])

                                                                            # To print a specific value (for example value at index 1)
                                                                            print([value for value in x.values()][1])

                                                                            # To print a pair of a key with its value (for example pair at index 2)
                                                                            print(([key for key in x.keys()][2], [value for value in x.values()][2]))

                                                                            # To print a key and a different value (for example key at index 0 and value at index 1)
                                                                            print(([key for key in x.keys()][0], [value for value in x.values()][1]))

                                                                            # To print all keys and values concatenated together
                                                                            print(''.join(str(key) + '' + str(value) for key, value in x.items()))

                                                                            # To print all keys and values separated by commas
                                                                            print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

                                                                            # To print all pairs of (key, value) one at a time
                                                                            for e in range(len(x)):
                                                                            print(([key for key in x.keys()][e], [value for value in x.values()][e]))

                                                                            # To print all pairs (key, value) in a tuple
                                                                            print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))






                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Nov 15 '18 at 2:13









                                                                            FouadDevFouadDev

                                                                            786




                                                                            786





















                                                                                0














                                                                                Try this:



                                                                                def name_the_key(dict, key):
                                                                                return key, dict[key]

                                                                                mydict = 'key1':1, 'key2':2, 'key3':3

                                                                                key_name, value = name_the_key(mydict, 'key2')
                                                                                print 'KEY NAME: %s' % key_name
                                                                                print 'KEY VALUE: %s' % value





                                                                                share|improve this answer



























                                                                                  0














                                                                                  Try this:



                                                                                  def name_the_key(dict, key):
                                                                                  return key, dict[key]

                                                                                  mydict = 'key1':1, 'key2':2, 'key3':3

                                                                                  key_name, value = name_the_key(mydict, 'key2')
                                                                                  print 'KEY NAME: %s' % key_name
                                                                                  print 'KEY VALUE: %s' % value





                                                                                  share|improve this answer

























                                                                                    0












                                                                                    0








                                                                                    0







                                                                                    Try this:



                                                                                    def name_the_key(dict, key):
                                                                                    return key, dict[key]

                                                                                    mydict = 'key1':1, 'key2':2, 'key3':3

                                                                                    key_name, value = name_the_key(mydict, 'key2')
                                                                                    print 'KEY NAME: %s' % key_name
                                                                                    print 'KEY VALUE: %s' % value





                                                                                    share|improve this answer













                                                                                    Try this:



                                                                                    def name_the_key(dict, key):
                                                                                    return key, dict[key]

                                                                                    mydict = 'key1':1, 'key2':2, 'key3':3

                                                                                    key_name, value = name_the_key(mydict, 'key2')
                                                                                    print 'KEY NAME: %s' % key_name
                                                                                    print 'KEY VALUE: %s' % value






                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered May 5 '11 at 23:24









                                                                                    fdbfdb

                                                                                    1,40511518




                                                                                    1,40511518





















                                                                                        0














                                                                                        key_name = '...'
                                                                                        print "the key name is %s and its value is %s"%(key_name, mydic[key_name])





                                                                                        share|improve this answer



























                                                                                          0














                                                                                          key_name = '...'
                                                                                          print "the key name is %s and its value is %s"%(key_name, mydic[key_name])





                                                                                          share|improve this answer

























                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            key_name = '...'
                                                                                            print "the key name is %s and its value is %s"%(key_name, mydic[key_name])





                                                                                            share|improve this answer













                                                                                            key_name = '...'
                                                                                            print "the key name is %s and its value is %s"%(key_name, mydic[key_name])






                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered May 6 '11 at 8:49









                                                                                            DonDon

                                                                                            11.1k74979




                                                                                            11.1k74979





















                                                                                                0














                                                                                                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)





                                                                                                share|improve this answer



























                                                                                                  0














                                                                                                  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)





                                                                                                  share|improve this answer

























                                                                                                    0












                                                                                                    0








                                                                                                    0







                                                                                                    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)





                                                                                                    share|improve this answer













                                                                                                    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)






                                                                                                    share|improve this answer












                                                                                                    share|improve this answer



                                                                                                    share|improve this answer










                                                                                                    answered Nov 6 '15 at 9:01









                                                                                                    JerilJeril

                                                                                                    2,2061633




                                                                                                    2,2061633





















                                                                                                        0














                                                                                                        I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:



                                                                                                        dict1 = 'random_word': [1,2,3]
                                                                                                        key_name = str([key for key in dict1]).strip("''")
                                                                                                        print(key_name) # equal to 'random_word', type: string.





                                                                                                        share|improve this answer



























                                                                                                          0














                                                                                                          I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:



                                                                                                          dict1 = 'random_word': [1,2,3]
                                                                                                          key_name = str([key for key in dict1]).strip("''")
                                                                                                          print(key_name) # equal to 'random_word', type: string.





                                                                                                          share|improve this answer

























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:



                                                                                                            dict1 = 'random_word': [1,2,3]
                                                                                                            key_name = str([key for key in dict1]).strip("''")
                                                                                                            print(key_name) # equal to 'random_word', type: string.





                                                                                                            share|improve this answer













                                                                                                            I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:



                                                                                                            dict1 = 'random_word': [1,2,3]
                                                                                                            key_name = str([key for key in dict1]).strip("''")
                                                                                                            print(key_name) # equal to 'random_word', type: string.






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Jan 27 '17 at 18:53









                                                                                                            PeaWagonPeaWagon

                                                                                                            2014




                                                                                                            2014















                                                                                                                protected by codeforester Oct 27 '18 at 22:22



                                                                                                                Thank you for your interest in this question.
                                                                                                                Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                Would you like to answer one of these unanswered questions instead?



                                                                                                                這個網誌中的熱門文章

                                                                                                                How to read a connectionString WITH PROVIDER in .NET Core?

                                                                                                                Node.js Script on GitHub Pages or Amazon S3

                                                                                                                Museum of Modern and Contemporary Art of Trento and Rovereto