293

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 be 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! :)

NerdOnTour
  • 634
  • 4
  • 15
neydroydrec
  • 6,973
  • 9
  • 57
  • 89
  • 24
    If you know what the specific key you want is, umm, you already know what the key is. – Wooble May 05 '11 at 22:52
  • Yes, but it's still helpful to be able to retrieve the key using code so that you can do things like determine its type (e.g. is it int32 vs. int64?) – KBurchfiel Mar 27 '22 at 05:15

19 Answers19

477

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • 1
    Although this worked beautifully for me in Python 2.7, what's the alternative in Py3k? I know `.iteritems()` is no longer supported... – Piper Mar 27 '13 at 21:18
  • 7
    @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
  • 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
151

Additionally you can use....

print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
Mason
  • 1,662
  • 1
  • 9
  • 10
  • 5
    The .keys() also print dict_keys([]) which someone might not need. In that case you need ", ".join(dictionary) . – thanos.a Oct 08 '21 at 09:44
40

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Dominic Santos
  • 1,900
  • 12
  • 14
  • 3
    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 06 '11 at 00: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 06 '11 at 00: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 06 '11 at 07:55
33
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()

Kumar
  • 918
  • 9
  • 19
ademar111190
  • 14,215
  • 14
  • 85
  • 114
24

The name of the key 'key_name' is 'key_name', therefore

print('key_name')

or whatever variable you have representing it.

cottontail
  • 10,268
  • 18
  • 50
  • 51
zenna
  • 9,006
  • 12
  • 73
  • 101
17

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))))
Fouad Boukredine
  • 1,495
  • 14
  • 18
13

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

Update for Python3: d.iteritems() is not longer supported in Python 3+ and should be replaced by d.items()

d_rev = {v: k for k, v in d.items()}
PacketLoss
  • 5,561
  • 1
  • 9
  • 27
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • Note (as above) that iteritems became simply 'items' in Python 3. – Mike Sep 24 '18 at 02:31
  • Caution: if you change `iteritems` to `items`, then as originally shown this answer will only return the first key -- if there are multiple matches. To solve this, create a blank list before the `for loop` (`values_list = []`), then append keys to this list (`values_list.append(k)`), in the `if` loop. Last, move the return statement (`return values_list`) outside the `for` loop. – Victoria Stuart Jul 16 '19 at 21:31
7
# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}

# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')

# programmatic method:
for key, value in mapping.items():
    print(f'{key}: {value}')

# yields:
# a 1
# b 2

# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))


# yields:
# a: 1
# b: 2

Edit: Updated for python 3's f-strings...

Brian Bruggeman
  • 5,008
  • 2
  • 36
  • 55
6

Make sure to do

dictionary.keys()

rather than

dictionary.keys
NerdOnTour
  • 634
  • 4
  • 15
kgui
  • 4,015
  • 5
  • 41
  • 53
5

Or you can do it that manner:

for key in my_dict:
     print key, my_dict[key]
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
5
import pprint
pprint.pprint(mydic.keys())
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
3
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)
Rob Wilson
  • 31
  • 3
2

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

2

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


Background

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

Find keys for given values

The following code correctly finds my keys, given values:

def k4v_edited(my_dict, value):
    values_list = []
    for k, v in my_dict.items():
        if v == value:
            values_list.append(k)
    return values_list

print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]

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

def k4v(my_dict, value):
    for k, v in my_dict.items():
        if v == value:
            return k

print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)

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

Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
2

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

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

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.
PeaWagon
  • 50
  • 1
  • 5
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)
Jeril
  • 7,858
  • 3
  • 52
  • 69
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
fdb
  • 1,998
  • 1
  • 19
  • 20
0
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
Don
  • 16,928
  • 12
  • 63
  • 101