How to print a dictionary's key?
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
add a comment |
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
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
add a comment |
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
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
python dictionary key
edited Oct 27 '18 at 22:23
codeforester
18.1k84264
18.1k84264
asked May 5 '11 at 22:51
BenjaminBenjamin
2,12863165
2,12863165
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
add a comment |
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
add a comment |
18 Answers
18
active
oldest
votes
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.
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
add a comment |
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.
2
the comma will leave them on the same line, but insert spaces between"is"
andkey
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
add a comment |
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
add a comment |
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()
add a comment |
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
add a comment |
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())
Note (as above) that iteritems became simply 'items' in Python 3.
– Mike
Sep 24 '18 at 2:31
add a comment |
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
add a comment |
What's wrong with using 'key_name'
instead, even if it is a variable?
it seemed wrong: but it isn't :) thanks.
– Benjamin
May 6 '11 at 10:42
add a comment |
import pprint
pprint.pprint(mydic.keys())
docs.python.org/2/library/pprint.html#pprint.pprint
– RzR
Jun 20 '15 at 13:01
add a comment |
# 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
add a comment |
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)
add a comment |
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
Why retrieve the value too though?
– Martijn Pieters♦
Jun 24 '17 at 12:32
add a comment |
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
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
add a comment |
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))))
add a comment |
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
add a comment |
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
add a comment |
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)
add a comment |
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.
add a comment |
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
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.
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
add a comment |
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.
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
add a comment |
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.
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.
edited Mar 27 '13 at 22:58
answered May 5 '11 at 23:21
juanchopanzajuanchopanza
189k21300411
189k21300411
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
add a comment |
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
add a comment |
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.
2
the comma will leave them on the same line, but insert spaces between"is"
andkey
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
add a comment |
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.
2
the comma will leave them on the same line, but insert spaces between"is"
andkey
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
add a comment |
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.
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.
edited Jun 24 '17 at 12:31
Martijn Pieters♦
714k13724952307
714k13724952307
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"
andkey
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
add a comment |
2
the comma will leave them on the same line, but insert spaces between"is"
andkey
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
add a comment |
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
add a comment |
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
add a comment |
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
answered Jul 15 '17 at 9:47
MasonMason
42649
42649
add a comment |
add a comment |
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()
add a comment |
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()
add a comment |
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()
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()
edited May 18 '18 at 15:14
kumsgs
465313
465313
answered Dec 18 '12 at 21:38
ademar111190ademar111190
8,941106290
8,941106290
add a comment |
add a comment |
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
add a comment |
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
add a comment |
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
The name of the key 'key_name' is key_name, therefore print 'key_name'
or whatever variable you have representing it.
answered May 5 '11 at 22:53
zennazenna
4,40095297
4,40095297
add a comment |
add a comment |
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())
Note (as above) that iteritems became simply 'items' in Python 3.
– Mike
Sep 24 '18 at 2:31
add a comment |
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())
Note (as above) that iteritems became simply 'items' in Python 3.
– Mike
Sep 24 '18 at 2:31
add a comment |
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())
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())
answered May 6 '11 at 0:57
Ned BatchelderNed Batchelder
258k53445567
258k53445567
Note (as above) that iteritems became simply 'items' in Python 3.
– Mike
Sep 24 '18 at 2:31
add a comment |
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
add a comment |
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
add a comment |
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
add a comment |
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
answered Sep 29 '15 at 11:44
Eugene SoldatovEugene Soldatov
6,9131833
6,9131833
add a comment |
add a comment |
What's wrong with using 'key_name'
instead, even if it is a variable?
it seemed wrong: but it isn't :) thanks.
– Benjamin
May 6 '11 at 10:42
add a comment |
What's wrong with using 'key_name'
instead, even if it is a variable?
it seemed wrong: but it isn't :) thanks.
– Benjamin
May 6 '11 at 10:42
add a comment |
What's wrong with using 'key_name'
instead, even if it is a variable?
What's wrong with using 'key_name'
instead, even if it is a variable?
answered May 5 '11 at 22:54
Ry-♦Ry-
169k40342359
169k40342359
it seemed wrong: but it isn't :) thanks.
– Benjamin
May 6 '11 at 10:42
add a comment |
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
add a comment |
import pprint
pprint.pprint(mydic.keys())
docs.python.org/2/library/pprint.html#pprint.pprint
– RzR
Jun 20 '15 at 13:01
add a comment |
import pprint
pprint.pprint(mydic.keys())
docs.python.org/2/library/pprint.html#pprint.pprint
– RzR
Jun 20 '15 at 13:01
add a comment |
import pprint
pprint.pprint(mydic.keys())
import pprint
pprint.pprint(mydic.keys())
answered May 6 '11 at 5:37
Matt JoinerMatt Joiner
56.3k75292461
56.3k75292461
docs.python.org/2/library/pprint.html#pprint.pprint
– RzR
Jun 20 '15 at 13:01
add a comment |
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
add a comment |
# 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
add a comment |
# 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
add a comment |
# 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
# 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
edited Feb 22 '18 at 17:52
DeadChex
2,7292029
2,7292029
answered Dec 20 '12 at 13:58
Brian BruggemanBrian Bruggeman
2,11412030
2,11412030
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
answered Jun 17 '15 at 10:54
Rob WilsonRob Wilson
112
112
add a comment |
add a comment |
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
Why retrieve the value too though?
– Martijn Pieters♦
Jun 24 '17 at 12:32
add a comment |
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
Why retrieve the value too though?
– Martijn Pieters♦
Jun 24 '17 at 12:32
add a comment |
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
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
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
add a comment |
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
add a comment |
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
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
add a comment |
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
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
add a comment |
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
Make sure to do
dictionary.keys()
# rather than
dictionary.keys
answered May 17 '18 at 14:25
CrtCrt
2,35522435
2,35522435
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
add a comment |
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
add a comment |
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))))
add a comment |
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))))
add a comment |
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))))
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))))
answered Nov 15 '18 at 2:13
FouadDevFouadDev
786
786
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
answered May 5 '11 at 23:24
fdbfdb
1,40511518
1,40511518
add a comment |
add a comment |
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
add a comment |
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
add a comment |
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
answered May 6 '11 at 8:49
DonDon
11k74979
11k74979
add a comment |
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
answered Nov 6 '15 at 9:01
JerilJeril
2,1731630
2,1731630
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jan 27 '17 at 18:53
PeaWagonPeaWagon
2014
2014
add a comment |
add a comment |
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?
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